package com.hsmw.api.controller.driver;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.NoRepeatSubmit;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.IDCardVerificationUtils;
import com.hsmw.api.controller.pub.RedisCache;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.controller.pub.VehicleLicenseCertOCR;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.utils.PlaceAnOrderUtils;
import com.hsmw.api.vo.*;
import com.hsmw.api.vo.DriverOrderInfoVO;
import com.hsmw.common.base.*;
import com.htn.common.core.base.BusinessType;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.DateUtil;
import com.htn.common.core.util.SendSmsUtil;
import com.htn.common.core.util.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.FAIL;
import static com.htn.common.core.constant.CommonConstants.ResponseStatus.SUCCESS;

@Api(tags = "司机端安卓端相关接口表")
@RestController
@RequestMapping(value = "/api/andro/driver")
public class HsmwDriverAndroController extends BaseController<HsmwDriverService, HsmwUserDriver> {


    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    @Autowired
    private HsmwItemService hsmwItemService;

    @Autowired
    private HsmwVehicleRefuelingMapper hsmwVehicleRefuelingMapper;

    @Autowired
    private HsmwOrderVehicleRequestMapper hsmwOrderVehicleRequestMapper;

    @Autowired
    private HsmwVehicleMapper hsmwVehicleMapper;

    @Autowired
    private HsmwOrderService hsmwOrderService;


    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;


    @Autowired
    private HsmwOrderForceManRelationService hsmwOrderForceManRelationService;


    @Autowired
    private HsmwUserDriverService hsmwUserDriverService;


    @Autowired
    private HsmwAuditService hsmwAuditService;


    @Autowired
    private HsmwDriverNewsService hsmwDriverNewsService;

    @Autowired
    private HsmwDriverClassService hsmwDriverClassService;


    @Autowired
    private HsmwOrderDistributeInfoService hsmwOrderDistributeInfoService;


    @Autowired
    private HsmwExchangeBusService hsmwExchangeBusService;

    @Autowired
    private HsmwForcemanAddressService hsmwForcemanAddressService;

    @Autowired
    private HsmwUserDriverMapper hsmwUserDriverMapper;

    @Autowired
    private HsmwRequestVehicleMapper hsmwRequestVehicleMapper;

    @Autowired
    private HsmwBanDriverService hsmwBanDriverService;

    @Autowired
    private HsmwPumpOperateRecordService hsmwPumpOperateRecordService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;


    @Autowired
    private HsmwDriverOrderRecordMapper hsmwDriverOrderRecordMapper;

    @Autowired
    private PlaceAnOrderUtils placeAnOrderUtils;

    @Autowired
    private HsmwScoringRecordMapper hsmwScoringRecordMapper;

    @Autowired
    private HsmwConstructionPositionService hsmwConstructionPositionService;

    @Autowired
    private HsmwOtherNoticeInfoMapper hsmwOtherNoticeInfoMapper;

    @Autowired
    private HsmwDriverUserMapper hsmwDriverUserMapper;

    @Autowired
    private HsmwDriverUserService hsmwDriverUserService;

    @Autowired
    private HsmwHtnUserService hsmwHtnUserService;


    @Autowired
    private HsmwUserService hsmwUserService;

    @Autowired
    private HsmwGasStationMapper gasStationMapper;

    @Autowired
    private HsmwDriverCancelOrderRecordService hsmwDriverCancelOrderRecordService;

    @Autowired
    private HsmwLeasingCompanyMapper hsmwLeasingCompanyMapper;

    @Autowired
    private HsmwPaymentRecordMapper hsmwPaymentRecordMapper;

    @Autowired
    private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;

    @Autowired
    private HsmwOrderBalanceMapper hsmwOrderBalanceMapper;

    @Autowired
    private HsmwRunSprintRecordMapper hsmwRunSprintRecordMapper;

    @Autowired
    private HsmwOrderMapper hsmwOrderMapper;

    @Autowired
    private HsmwItemLinkmanMapper hsmwItemLinkmanMapper;

    @Autowired
    private HsmwSituationReportService hsmwSituationReportService;

    @Autowired
    private HsmwHelpCenterService hsmwHelpCenterService;


    @Value(value = "${sms.appKey}")
    private String appKey;
    @Value(value = "${sms.channel}")
    private String channel;
    @Value(value = "${sms.smsSign}")
    private String smsSign;
    @Value(value = "${sms.appId}")
    private int appId;
    @Value(value = "${sms.driverCancelOrder}")
    private int driverCancelOrder;
    @Value(value = "${sms.positionErrorRecovery}")
    private int positionErrorRecovery;
    @Value(value = "${sms.workFinishFive}")
    private int workFinishFive;
    @Value(value = "${sms.workFinishHour}")
    private int workFinishHour;



    /**
     * 司机信息认证
     *
     * @param
     * @return
     */
    @ApiOperation(value = "身份证 信息认证", notes = "身份信息认证", produces = "application/json")
    @PostMapping("/idCardAnthentic")
    public DataResponse idCardAnthentic(@RequestBody IDCardVericationVO vo) {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();

            if (StringUtils.isBlank(vo.getIDCard())) {
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的身份证号为空，请重新输入！");
            }
            if (StringUtils.isBlank(vo.getName())) {
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的姓名为空，请重新输入！");
            }
            //hsmwAuditService.saveOrUpdateHsmwAudit(hsmwAudit);
            IDCardVericationVO vo1 = IDCardVerificationUtils.iDCardVerification(vo);
            if ("0".equals(vo1.getCode())) {
                LambdaQueryWrapper<HsmwAudit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(HsmwAudit::getUserId, hsmwUser.getId());
                List<HsmwAudit> list = hsmwAuditService.list(lambdaQueryWrapper);
                HsmwAudit audit = new HsmwAudit();
                if (StringUtils.isListNotNull(list)) {
                    audit = list.get(0);
                    audit.setIdCardFront(vo.getIdCardFront());
                    audit.setIdCardFrontId(vo.getIdCardFrontId());
                    audit.setIdCardBack(vo.getIdCardBack());
                    audit.setIdCardBackId(vo.getIdCardBackId());
                    audit.setIdCard(vo.getIDCard());
                    audit.setName(vo.getName());
                    audit.setUsername(hsmwUser.getUsername());
                    audit.setUserId(hsmwUser.getId());
                    audit.setAuditTime(null);
                    //audit.setAuditStatus("审核中");
                    hsmwAuditService.updateById(audit);
                } else {
                    audit.setIdCardFront(vo.getIdCardFront());
                    audit.setIdCardFrontId(vo.getIdCardFrontId());
                    audit.setIdCardBack(vo.getIdCardBack());
                    audit.setIdCardBackId(vo.getIdCardBackId());
                    audit.setIdCard(vo.getIDCard());
                    audit.setName(vo.getName());
                    audit.setUsername(hsmwUser.getUsername());
                    audit.setUserId(hsmwUser.getId());
                    audit.setAuditTime(null);
                    //audit.setAuditStatus("审核中");
                    hsmwAuditService.save(audit);
                }
                IDCardVericationVO vos = new IDCardVericationVO();
                vos.setIDCard(vo.getIDCard());
                vos.setName(vo.getName());
                return new DataResponse(vos);
            } else {
                return new DataResponse(vo1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.SYSTEM_ERROR, "司机认证信息新增或修改异常，请联系系统管理员！");
        }
    }


    /**
     * 司机信息认证
     *
     * @param
     * @return
     */
    @ApiOperation(value = "司机信息认证", notes = "司机信息认证", produces = "application/json")
    @PostMapping("/driverInfoAnthentic")
    public DataResponse driverInfoAnthentic(@RequestBody HsmwAudit hsmwAudit) {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            LambdaQueryWrapper<HsmwAudit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HsmwAudit::getUserId, hsmwUser.getId());
            List<HsmwAudit> list = hsmwAuditService.list(lambdaQueryWrapper);
            HsmwAudit audit = new HsmwAudit();
            if (StringUtils.isListNotNull(list)) {
                audit = list.get(0);
                hsmwAudit.setId(audit.getId());
            }
            //hsmwAudit.setAuditStatus("审核中");
            hsmwAudit.setUserId(hsmwUser.getId());
            hsmwAudit.setAuditTime(null);
            hsmwAuditService.saveOrUpdateHsmwAudit(hsmwAudit);
            HashMap result = new HashMap();
            if (StringUtils.isNotBlank(hsmwAudit.getAuditStatus())) {
                result.put("auditStatus", "审核中");
            }
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.SYSTEM_ERROR, "司机身份证信息校验异常，请联系系统管理员！");
        }
    }

    /**
     * 查询司机端查询司机端的进行中的订单的进行中的订单
     *
     * @param
     * @returnqw
     */
    @ApiOperation(value = "查询司机端的进行中的当前订单", notes = "查询司机端的进行中的订单", produces = "application/json")
    @PostMapping("/getGoingOrders")
    public DataResponse getGoingOrders() {
        try {

            String status = "";
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwUserDriver driver = hsmwUserDriverService.getBizDriverByUserId(hsmwUser.getId());
            if (StringUtils.isNull(driver)) {
                status = CommonConstants.DRIVER_FREE;
            } else if (StringUtils.isNull(driver.getWorkStatus())) {
                status = CommonConstants.DRIVER_FREE;
            } else {
                status = driver.getWorkStatus();
            }
            int minutes = 0;
            int workTime = 0;
            String key = "driver:status:"+driver.getId();
            String keys = "vehicle:automatic:"+driver.getVehicleId();
            Date date = Date.from(LocalDateTime.now().atZone( ZoneId.systemDefault()).toInstant());
            if(redisTemplate.hasKey(key)){
                String time = (String) redisTemplate.opsForValue().get(key);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date agoTime = formatter.parse(time);
                minutes = DateUtil.getOffsetMinutes(agoTime, date);
            }else {
                redisTemplate.opsForValue().set(key,LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }

            HashMap result = new HashMap();
            result.put("time", minutes);
            if (StringUtils.isBlank(driver.getVehicleId())) {
                result.put("orderList", new ArrayList<>());
                result.put("workStatus", status);
                return new DataResponse(result);
            }
            if(redisTemplate.hasKey(keys)){
                result.put("automatic", "1");
            }
            HashMap param = new HashMap();
            param.put("vehicleId", driver.getVehicleId());
            List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
            for (CurrentOrderInfoVO currentOrderInfoVO : orderList) {
                String itemId = currentOrderInfoVO.getItemId();
                List<HsmwForcemanAddress> hsmwForcemanAddresses = hsmwForcemanAddressService.list(new LambdaQueryWrapper<HsmwForcemanAddress>()
                        .eq(HsmwForcemanAddress::getItemId, itemId));
                if (CollectionUtil.isNotEmpty(hsmwForcemanAddresses)) {
                    result.put("Address", hsmwForcemanAddresses);
                }
                // 通过订单id查看订单下的车辆信息
                List<VehicleStatisticsVO> vehicleStatisticsVOS = hsmwOrderVehicleRequestMapper.findVehicleInfoByOrderId(currentOrderInfoVO.getOrderId());
                currentOrderInfoVO.setVehicleStatisticsVOS(vehicleStatisticsVOS);

                HashMap map = new HashMap();
                map.put("orderId",currentOrderInfoVO.getOrderId());
                List<HsmwConstructionPosition> ps= hsmwOrderMapper.selectPositionsByOrderId(map);
                if(CollectionUtil.isNotEmpty(ps)){
                    currentOrderInfoVO.setHsmwConstructionPositions(ps);
                }

                if(StringUtils.isNotBlank(currentOrderInfoVO.getLinkmanType())){
                    if(StringUtils.equals(LinkmanTypeEnum.FOREMAN.getValue(),currentOrderInfoVO.getLinkmanType()) || StringUtils.equals(LinkmanTypeEnum.PROJECTMAN.getValue(),currentOrderInfoVO.getLinkmanType())){
                        HsmwHtnUser byId = hsmwHtnUserService.getById(currentOrderInfoVO.getLinkmanId());
                        if(StringUtils.isNotBlank(byId.getAvatar())){
                            currentOrderInfoVO.setAvatar(byId.getAvatar());
                        }
                    }
                }

                break;
            }
            if(CollectionUtil.isNotEmpty(orderList)){
                if(orderList.get(0).getStartWorkTime() != null){
                    LocalDateTime startWorkTime = orderList.get(0).getStartWorkTime();
                    Date workTimes = Date.from(startWorkTime.atZone(ZoneId.systemDefault()).toInstant());
                    workTime = DateUtil.getOffsetMinutes(workTimes, date);
                    result.put("workTime", workTime);
                }

            }
            String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
            System.err.println(format);
            Integer orderCount = hsmwDriverOrderRecordMapper.queryOrderCount(driver.getId(),format);

            String sumVolume = hsmwDriverOrderRecordMapper.queryDriverSumVolumeById(driver.getId(),format);

            result.put("orderCount", orderCount);
            result.put("sumVolume", sumVolume);
            result.put("orderList", orderList);
            result.put("workStatus", status);

            HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(driver.getVehicleId());
            if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(), hsmwVehicle.getFlag(), hsmwVehicle.getIdentifyingCode());
                if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                    hsmwVehicle.setImeiNumLocate(entity.getGpsLon() + "," + entity.getGpsLat());
                }
                result.put("MobileLocate", hsmwVehicle.getImeiNumLocate());
            }
            //查询 方量统计
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "查询司机端的进行中的当前订单失败，请联系管理员！");
        }
    }


    /**
     * 查询我的系统消息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "查询我的系统消息", notes = "查询我的系统消息", produces = "application/json")
    @PostMapping("/getSystemMsg")
    public DataResponse getSystemMsg(@RequestBody BasePage<HsmwDriverNews> basePage) {
        try {
            IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
            HsmwDriverNews hsmwRole = basePage.getRequestData();
            Assert.notNull(page.getCurrent(), "页码不能为空");
            Assert.notNull(page.getSize(), "页码不能为空");
            IPage<HsmwDriverNews> data = hsmwDriverNewsService.getHsmwNewsPage(page, hsmwRole);
            return new DataResponse(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "查询我的系统消息，请联系管理员！");
        }
    }


    /**
     * 查询司机端的我的订单列表的信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "查询当前司机下面的所有的订单", notes = "查询工长端的订单列表的信息", produces = "application/json")
    @PostMapping("/getOrderStatistics")
    public DataResponse getOrderInfoByStatus(@RequestBody OrderQueryParam status) {
        if (StringUtils.isBlank(status.getStatus())) {
            return new DataResponse("您输入的订单状态为空，请重新输入！");
        }
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            //获取工长所在项目的项目名称和项目id。
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            if (!OrderStatusEnum.ALL.getValue().equals(status.getStatus())) {
                param.put("status", status.getStatus());
            }
            param.put("userId", hsmwUser.getId());
            List<DriverOrderInfoVO> orderList = hsmwOrderService.getOrderListByParam(param);
            result.put("orderList", orderList);
            //查询 方量统计
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取订单列表失败，请联系管理员！");
        }
    }

    /**
     * 根据订单ID查询订单详情
     *
     * @param
     * @return
     */
    @ApiOperation(value = "根据订单ID查询订单详情", notes = "根据订单ID查询订单详情", produces = "application/json")
    @PostMapping("/orderInfo")
    public DataResponse getOrderDetail(@RequestBody OrderQueryParam orderQueryParam) {
        if (StringUtils.isBlank(orderQueryParam.getOrderId())) {
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的订单id为空！");
        }
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            LambdaQueryWrapper<HsmwUserDriver> driverLambdaQueryWrapper = new LambdaQueryWrapper<>();
            driverLambdaQueryWrapper.eq(HsmwUserDriver::getUserId, hsmwUser.getId());
            HsmwUserDriver driver = hsmwUserDriverService.getOne(driverLambdaQueryWrapper);

            HashMap result = new HashMap();
            HsmwOrder order = hsmwOrderService.getById(orderQueryParam.getOrderId());

            LambdaQueryWrapper<HsmwOrderVehicleRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HsmwOrderVehicleRelation::getOrderId, orderQueryParam.getOrderId());
            lambdaQueryWrapper.eq(HsmwOrderVehicleRelation::getVehicleId, driver.getVehicleId());
            lambdaQueryWrapper.orderByDesc(HsmwOrderVehicleRelation::getCreateTime);
            List<HsmwOrderVehicleRelation> orderVehicleRelations = hsmwOrderVehicleRelationService.list(lambdaQueryWrapper);
            HsmwOrderVehicleRelation orderVehicleRelation = orderVehicleRelations.get(0);
            OrderDetailInnfoVO vo = new OrderDetailInnfoVO();
            if (StringUtils.isNotNull(orderVehicleRelation)) {
                vo.setVehicleModel(orderVehicleRelation.getVehicleModel());
                vo.setVehicleType(orderVehicleRelation.getVehicleType());
                vo.setDriverVolume(orderVehicleRelation.getDriverVolume());
                vo.setRealVolume(orderVehicleRelation.getRealVolume());
                vo.setClockInTime(orderVehicleRelation.getClockInTime());
                DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                vo.setEndTime(orderVehicleRelation.getEndTime());
                vo.setOrderStatus(orderVehicleRelation.getOrderStatus());
            }
            result.put("detailInfo", vo);
            result.put("orderInfo", order);
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取订单详情失败，请联系管理员！");
        }
    }


    /**
     * 修改司机工作状态
     *
     * @param
     * @return
     */
    @ApiOperation(value = "修改司机工作状态", notes = "修改司机工作状态", produces = "application/json")
    @PostMapping("/updateWordStatus")
    public DataResponse updateWordStatus(@RequestBody OrderQueryParam orderQueryParam) {
        try {
            if (StringUtils.isBlank(orderQueryParam.getWorkStatus())) {
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的工作状态为空，请重新输入！");
            }
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            if (CommonConstants.DRIVER_ACCEPT_ORDER.equals(orderQueryParam.getWorkStatus())) {
                LambdaQueryWrapper<HsmwAudit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(HsmwAudit::getUserId, hsmwUser.getId());
                List<HsmwAudit> hsmwAuditList = hsmwAuditService.list(lambdaQueryWrapper);
                LambdaQueryWrapper<HsmwUserDriver> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(HsmwUserDriver::getUserId, hsmwUser.getId());
                HsmwUserDriver driver = hsmwUserDriverService.getOne(lambdaQueryWrapper1);
                if (StringUtils.isListNull(hsmwAuditList)) {
                    if (StringUtils.isNull(driver)) {
                        return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您还未认证信息，不能修改为接单中！");
                    }
                } else {
                    HsmwAudit audit = hsmwAuditList.get(0);
                    if (StringUtils.isBlank(audit.getAuditStatus()) || !CommonConstants.AUDIT_COMPLETE.equals(audit.getAuditStatus())) {
                        return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您的认证还未通过，不能修改为接单中！");
                    }
                }
            }
            LambdaQueryWrapper<HsmwUserDriver> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(HsmwUserDriver::getUserId, hsmwUser.getId());
            HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getOne(lambdaQueryWrapper1);
            if (StringUtils.isNull(hsmwUserDriver)) {
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您的认证还未通过，不能修改为接单中！");
            }
            //查询司机的状态 是 接单中 还是 休息中
            hsmwUserDriver.setWorkStatus(orderQueryParam.getWorkStatus());
            hsmwUserDriverService.saveOrUpdateDriverStatus(hsmwUserDriver);
            return new DataResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "修改司机工作状态，请联系管理员！");
        }
    }


    /**
     * 司机查看我的业绩  ====已经修改
     *
     * @param
     * @return
     */
    @Log(title = "司机端：业绩统计菜单： 司机查看我的业绩", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机端：业绩统计菜单： 司机查看我的业绩", notes = "司机查看我的业绩", produces = "application/json")
    @PostMapping("/getOrderInfoStatistics")
    public DataResponse getOrderInfoCount(@RequestBody OrderQueryVO orderQueryVO) {

        LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
        HsmwUserDriver driver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>()
                .eq(HsmwUserDriver::getUserId, hsmwUser.getId()));
        String[] params = orderQueryVO.getQueryDate().split("-");
        int year = Integer.parseInt(params[0]);
        int month = Integer.parseInt(params[1]);
        HashMap param = new HashMap();
        if (StringUtils.isNotEmpty(year + "")) {
            param.put("year", year);
        }
        if (StringUtils.isNotEmpty(month + "")) {
            param.put("month", month);
        }
        param.put("userId", hsmwUser.getId());
        try {
            List<DriverOrderResultVO> vehicleRelationList = null;
            if (StringUtils.equals(orderQueryVO.getFlag(), "finish")) {
                param.put("vehicleId", driver.getId());
                vehicleRelationList = hsmwOrderVehicleRelationService.getOrderInfoStatistics(param);
                for (DriverOrderResultVO driverOrderResultVO : vehicleRelationList) {
                    if(StringUtils.equals("线下",driverOrderResultVO.getRemark())){
                        driverOrderResultVO.setConstructionPosition(driverOrderResultVO.getPosition());
                    }
                }
            } else {
                if(StringUtils.isNotBlank(driver.getVehicleId())){
                    param.put("vehicleId", driver.getVehicleId());
                    vehicleRelationList = hsmwOrderVehicleRelationService.getCancelOrderInfoStatistics(param);
                }else {
                    vehicleRelationList = new ArrayList<>();
                }
            }
            HashMap result = new HashMap();
            int orderCount = 0;
            double volumeCount = 0.00;
            double sumVolumeCount = 0.00;
            if (StringUtils.isListNotNull(vehicleRelationList)) {
                orderCount = vehicleRelationList.size();
                for (DriverOrderResultVO vo : vehicleRelationList) {
                    if (StringUtils.isNotBlank(vo.getCompleteVolume())) {
                        volumeCount += Double.valueOf(vo.getCompleteVolume());
                    }
                    if (StringUtils.isNotBlank(vo.getSettlementVolume())) {
                        sumVolumeCount += Double.valueOf(vo.getSettlementVolume());
                    }
                }
                result.put("orderList", vehicleRelationList);
            } else {
                result.put("orderList", new ArrayList<>());
            }
            result.put("sumVolumeCount", String.format("%.1f", sumVolumeCount));
            result.put("orderCount", orderCount);
            result.put("volumeCount", String.format("%.1f", volumeCount));
            //查询 方量统计
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取我的业绩失败，请联系管理员！");
        }
    }


    /**
     * 司机查看我的认证
     *
     * @param
     * @return
     */
    @Log(title = "司机查看我的认证", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查看我的认证", notes = "司机查看我的认证", produces = "application/json")
    @PostMapping("/myAuditInfo")
    public DataResponse myAuditInfo() {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            HashMap result = new HashMap();

            LambdaQueryWrapper<HsmwAudit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HsmwAudit::getUserId, hsmwUser.getId());

            List<HsmwAudit> hsmwAuditList = hsmwAuditService.list(lambdaQueryWrapper);

            if (StringUtils.isListNull(hsmwAuditList)) {
                result.put("auditInfo", new HsmwAudit());
            } else {
                HsmwAudit hsmwAudit = hsmwAuditList.get(0);
                result.put("auditInfo", hsmwAudit);
            }
            //查询 方量统计
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取我的认证失败，请联系管理员！");
        }
    }


    /**
     * 司机进入我的所需信息
     *
     * @param
     * @return
     */
    @Log(title = "司机进入我的所需信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机进入我的所需信息", notes = "司机进入我的所需信息", produces = "application/json")
    @PostMapping("/aboutMe")
    public DataResponse aboutMe() {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            HashMap result = new HashMap();
            LambdaQueryWrapper<HsmwAudit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(HsmwAudit::getUserId, hsmwUser.getId());
            List<HsmwAudit> hsmwAuditList = hsmwAuditService.list(lambdaQueryWrapper);
            LambdaQueryWrapper<HsmwUserDriver> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(HsmwUserDriver::getUserId, hsmwUser.getId());
            HsmwUserDriver driver = hsmwUserDriverService.getOne(lambdaQueryWrapper1);
            DriverAboutMeVO driverAboutMeVO = new DriverAboutMeVO();
            driverAboutMeVO.setUserId(hsmwUser.getId());
            if (StringUtils.isNotNull(driver)) {
                if (StringUtils.isBlank(driver.getVehicleId())) {
                    result.put("driverStatus", "noVehicle");
                }
                HashMap param = new HashMap();
                param.put("driverId", driver.getId());
                DriveTotalInfoVO vo = hsmwUserDriverService.getDriverTotalInfo(param);
                driverAboutMeVO.setDriverId(driver.getId());
                driverAboutMeVO.setDriverName(vo.getDriverName());
                driverAboutMeVO.setDriverTelphoneNum(vo.getDriverTelNum());
                driverAboutMeVO.setHistoryOrderCount(vo.getHistoryOrderCount());
                driverAboutMeVO.setHeadProfile(vo.getHeadProfile());
                driverAboutMeVO.setScore(vo.getScore());
            }
            String auditStatus = "";
            if (StringUtils.isListNull(hsmwAuditList)) {
                if (StringUtils.isNull(driver)) {
                    auditStatus = "未认证";
                } else {
                    auditStatus = "已认证";
                }
            } else {
                HsmwAudit hsmwAudit = hsmwAuditList.get(0);
                if (CommonConstants.AUDIT_ING.equals(hsmwAudit.getAuditStatus())) {
                    auditStatus = "认证中";
                }
                if (CommonConstants.AUDIT_COMPLETE.equals(hsmwAudit.getAuditStatus())) {
                    auditStatus = "已认证";
                }
                if (CommonConstants.AUDIT_FAILURE.equals(hsmwAudit.getAuditStatus())) {
                    auditStatus = "认证失败";
                }
                if (StringUtils.isBlank(hsmwAudit.getAuditStatus())) {
                    auditStatus = "未认证";
                }
            }
            result.put("auditStatus", auditStatus);
            result.put("driverInfo", driverAboutMeVO);
            //查询 方量统计
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取我的认证失败，请联系管理员！");
        }
    }

    /**
     * 完成订单
     * <p>
     * UNRECEIVED("1", "等待接单"),
     * UNSETOUT("2", "等待出发"),
     * SETOUT("3", "已出发"),
     * ARRIVED("4","已到达"),
     * WORKING("5","工作中"),
     * COMPLETED("6","已完成"),
     * CANCELED("7","已取消"),
     * ALL("all","全部");
     *
     * @param
     * @returnsij
     */
    @Log(title = "司机更新子订单状态信息", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新订单状态信息： ", notes = "完成订单", produces = "application/json")
    @PostMapping("/updateOrderInfo")
    public DataResponse updateOrderInfo(@RequestBody OrderQueryParam orderQueryParam) {
        if (StringUtils.isBlank(orderQueryParam.getOrderId())) {
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的订单id为空！");
        }
        if (StringUtils.isBlank(orderQueryParam.getStatus())) {
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的订单状态为空！");
        }
        if (ChildOrderStatusEnum.COMPLETED.getValue().equals(orderQueryParam.getStatus()) && StringUtils.isBlank(orderQueryParam.getDriverVolume())) {
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的方量为空！");
        }

        try {
            return hsmwUserDriverService.updateOrderStatusInfo(orderQueryParam);

        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "更新订单信息失败，请联系管理员！");
        }
    }

    /*
     * 司机端获取待接单的订单列表
     *
     * @param
     * @return
     **/
    @ApiOperation(value = "司机端获取待接单的订单列表", notes = "司机端获取待接单的订单列表", produces = "application/json")
    @PostMapping("/taskingOrderList")
    public DataResponse taskingOrderList() {
        try {
            HashMap result = new HashMap();
            List<TaskingOrderVO> taskingOrderVOList = hsmwUserDriverService.taskingOrderList();

            for (TaskingOrderVO taskingOrderVO : taskingOrderVOList) {
                String vehicleId = taskingOrderVO.getVehicleId();
                HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(vehicleId);
                taskingOrderVO.setVehicleModel(hsmwVehicle.getVehicleModel());
                taskingOrderVO.setVehicleType(hsmwVehicle.getVehicleType());
                if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                    GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(), hsmwVehicle.getFlag(), hsmwVehicle.getIdentifyingCode());
                    if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                        taskingOrderVO.setMobileLocate(entity.getGpsLon() + "," + entity.getGpsLat());
                    }
                }
            }
            result.put("orderList", taskingOrderVOList);
            System.out.println("待抢单列表的返回信息  ===========" + JSON.toJSONString(taskingOrderVOList));
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "司机端获取待接单的订单列表，请联系管理员！");
        }
    }


    /**
     * 抢单接口
     *
     * @param
     * @return
     */
  /*  @ApiOperation(value = "抢单接口  ", notes = "抢单接口", produces = "application/json")
    @PostMapping("/grabbingOrders")
    public DataResponse grabbingOrders(@RequestBody OrderQueryParam orderQueryParam) {
        try {
            return hsmwUserDriverService.grabbingOrders(orderQueryParam);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "抢单异常，请联系管理员！");
        }

    }
*/

    /**
     * 抢单接口
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取抢单结果  ", notes = "获取抢单结果", produces = "application/json")
    @PostMapping("/getGrabbingResult")
    public DataResponse getGrabbingResult(@RequestBody OrderQueryParam orderQueryParam) {
        try {
            LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwUserDriver driver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>()
                    .eq(HsmwUserDriver::getUserId, currentUser.getId()));
            orderQueryParam.setDriverId(driver.getId());
            orderQueryParam.setVehicleId(driver.getVehicleId());
            return hsmwUserDriverService.getGrabbingResult(orderQueryParam);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取抢单结果异常，请联系管理员！");
        }

    }


    /**
     * 获取认证所需要的字典
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取认证  所需要的字典", notes = "获取认证 所需要的字典", produces = "application/json")
    @PostMapping("/getDictInfo")
    public DataResponse getOrderCreateInfo() {
        try {
            HashMap result = hsmwOrderService.getOrderDictInfo();
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取订单创建所需要的字典和工长列表失败，请联系管理员！");
        }
    }


    /**
     * 行驶证OCR
     *
     * @param
     * @return
     */
    @ApiOperation(value = "行驶证OCR", notes = "行驶证OCR", produces = "application/json")
    @PostMapping("/vehicleLicenceOCR")
    public DataResponse vehicleLicenceOCR(@RequestBody VehicleLicenceReqVO vehicleLicenceReqVO) {
        try {
            if (CommonConstants.BACK.equals(vehicleLicenceReqVO.getCarSide()) && StringUtils.isBlank(vehicleLicenceReqVO.getBackImageUrl())) {
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "行驶证的背面图片URL为空，请重新输入！");
            }
            if (CommonConstants.FRONT.equals(vehicleLicenceReqVO.getCarSide()) && StringUtils.isBlank(vehicleLicenceReqVO.getFrontImageUrl())) {
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "行驶证的正面图片URL为空，请重新输入！");
            }
            DataResponse resp = VehicleLicenseCertOCR.ocr(vehicleLicenceReqVO);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "行驶证OCR异常，请联系管理员！");
        }
    }


    /**
     * 行驶证OCR
     *
     * @param
     * @return
     */
    @ApiOperation(value = "驾驶证OCR", notes = "驾驶证OCR", produces = "application/json")
    @PostMapping("/driverLicenceOCR")
    public DataResponse driverLicenceOCR(@RequestBody DriverLicenceReqVO vehicleLicenceReqVO) {
        try {
            if (CommonConstants.FRONT.equals(vehicleLicenceReqVO.getCarSide()) && StringUtils.isBlank(vehicleLicenceReqVO.getFrontImageUrl())) {
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "行驶证的正面图片URL为空，请重新输入！");
            }
            DataResponse resp = VehicleLicenseCertOCR.driverLicenceocr(vehicleLicenceReqVO);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "驾驶证OCR异常，请联系管理员！");
        }
    }

    /**
     * 将系统信息更新为已读
     *
     * @param
     * @return
     */
    @ApiOperation(value = "将系统信息更新为已读", notes = "将系统信息更新为已读", produces = "application/json")
    @PostMapping("/updateAlreadyRead")
    public DataResponse updateAlreadyRead() {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            HashMap param = new HashMap();
            param.put("userId", hsmwUser.getId());
            hsmwDriverNewsService.updateAlreadyRead(param);
            return new DataResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "将系统信息更新为已读，请联系管理员！");
        }
    }

    /**
     * 司机端获取待接单的订单列表
     *
     * @param
     * @return
     */

    @ApiOperation(value = "司机端获取同行的司机的列表", notes = "司机端获取同行的司机的列表", produces = "application/json")
    @PostMapping("/orderPeerDrivers")
    public DataResponse orderPeerDrivers(@RequestBody OrderQueryParam orderQueryParam) {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            param.put("userId", hsmwUser.getId());
            param.put("orderId", orderQueryParam.getOrderId());
            List<PeerDriverVO> taskingOrderVOList = hsmwUserDriverService.orderPeerDrivers(param);
            result.put("peerList", taskingOrderVOList);
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取订单详情失败，请联系管理员！");
        }
    }


    /**
     * 司机提交遇到的问题
     *
     * @param
     * @return
     */
    @ApiOperation(value = "司机提交遇到的问题 ", notes = "司机提交遇到的问题", produces = "application/json")
    @PostMapping("/submitProblem")
    public DataResponse submitProblem(@RequestBody SubmitProblemVO submitProblemVO) {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            hsmwUserDriverService.saveProblemInfo(submitProblemVO);
            return new DataResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取订单详情失败，请联系管理员！");
        }
    }

    /**
     * 获取司机个人信息卡片信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "司机：获取司机个人信息卡片信息", notes = "获取司机个人信息卡片信息", produces = "application/json")
    @PostMapping("/getDriverTotalInfo/{userId}")
    public DataResponse getDriverTotalInfo(@PathVariable(value = "userId") String userId) {
        try {
            HashMap param = new HashMap();
            param.put("userId", userId);
            DriveTotalInfoVO driveTotalInfoVO = hsmwUserDriverService.getAndroDriverTotalInfo(param);
            List<HsmwVehicleRefueling> hsmwVehicleRefuelings = hsmwVehicleRefuelingMapper.selectList(new LambdaQueryWrapper<HsmwVehicleRefueling>().eq(HsmwVehicleRefueling::getDriverId, driveTotalInfoVO.getDriverId()).orderByDesc(HsmwVehicleRefueling::getCreateTime).last("LIMIT 1"));
            if (CollectionUtil.isNotEmpty(hsmwVehicleRefuelings)) {
                driveTotalInfoVO.setSubmitTime(hsmwVehicleRefuelings.get(0).getSubmitTime());
            }
            // 获取司机id
            String driverId = driveTotalInfoVO.getDriverId();
            // 查询司机学习信息
            List<HsmwDriverClass> driverClassList = hsmwDriverClassService.list(new LambdaQueryWrapper<HsmwDriverClass>().eq(HsmwDriverClass::getDriverId, driverId));
            if (CollectionUtil.isNotEmpty(driverClassList)) {
                for (HsmwDriverClass hsmwDriverClass : driverClassList) {
                    if (StringUtils.equals("泵车使用与常见故障处理", hsmwDriverClass.getHomeName())) {
                        long progress = Long.parseLong(hsmwDriverClass.getProgress());
                        if (progress < 100) {
                            driveTotalInfoVO.setVehicleUseAndCommonTroubleshooting("0");
                        } else {
                            driveTotalInfoVO.setVehicleUseAndCommonTroubleshooting("1");
                        }
                    }
                    if (StringUtils.equals("交通事故处理与应急救护", hsmwDriverClass.getHomeName())) {
                        long progress = Long.parseLong(hsmwDriverClass.getProgress());
                        if (progress < 100) {
                            driveTotalInfoVO.setTrafficAccidentTreatmentAndEmerRescue("0");
                        } else {
                            driveTotalInfoVO.setTrafficAccidentTreatmentAndEmerRescue("1");
                        }
                    }
                    if (StringUtils.equals("职业道德与服务规范", hsmwDriverClass.getHomeName())) {
                        long progress = Long.parseLong(hsmwDriverClass.getProgress());
                        if (progress < 100) {
                            driveTotalInfoVO.setWorkEthicAndServiceSpecification("0");
                        } else {
                            driveTotalInfoVO.setWorkEthicAndServiceSpecification("1");
                        }
                    }
                    if (StringUtils.equals("安全运营与治安规范", hsmwDriverClass.getHomeName())) {
                        long progress = Long.parseLong(hsmwDriverClass.getProgress());
                        if (progress < 100) {
                            driveTotalInfoVO.setSafeOperandProfSpecifications("0");
                        } else {
                            driveTotalInfoVO.setSafeOperandProfSpecifications("1");
                        }
                    }

                }
            } else {
                driveTotalInfoVO.setSafeOperandProfSpecifications("0");
                driveTotalInfoVO.setTrafficAccidentTreatmentAndEmerRescue("0");
                driveTotalInfoVO.setVehicleUseAndCommonTroubleshooting("0");
                driveTotalInfoVO.setWorkEthicAndServiceSpecification("0");
            }
            String vehicleId = driveTotalInfoVO.getVehicleId();
            List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, vehicleId));
            List<DriverDetailInfoVO> driverDetailInfoVOS = new ArrayList<>();
            for (HsmwUserDriver hsmwUserDriver : hsmwUserDrivers) {
                DriverDetailInfoVO driverDetailInfoVO = new DriverDetailInfoVO();
                if(StringUtils.equals(hsmwUserDriver.getUserId(),userId)){
                    continue;
                }
                HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(hsmwUserDriver.getUserId());
                driverDetailInfoVO.setScore(hsmwUserDriver.getScore());
                driverDetailInfoVO.setName(hsmwDriverUser.getName());
                driverDetailInfoVO.setUsername(hsmwDriverUser.getUsername());
                driverDetailInfoVO.setAvatar(hsmwDriverUser.getAvatar());
                driverDetailInfoVOS.add(driverDetailInfoVO);
            }
            driveTotalInfoVO.setDriverDetailInfoVOS(driverDetailInfoVOS);

            return new DataResponse(driveTotalInfoVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "获取订单详情失败，请联系管理员！");
        }
    }


    /**
     * 取消订单
     *
     * @param
     * @return
     */

    @ApiOperation(value = "取消订单", notes = "取消订单", produces = "application/json")
    @PostMapping("/cancelOrder")
    public DataResponse cancelOrder(@RequestBody OrderQueryParam orderQueryParam) {
        if (StringUtils.isBlank(orderQueryParam.getOrderId())) {
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "您输入的订单id为空！");
        }
        try {
            return hsmwUserDriverService.cancelOrder(orderQueryParam);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "取消订单失败，请联系管理员！");
        }
    }


    /**
     * 搜索关键词位置信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "司机：打电话接口： 子订单id：orderVehicleRelationId必输 ，订单ID ：orderId 必输；目标电话： toPhoneNum ", notes = "司机：打电话接口", produces = "application/json")
    @PostMapping("/getVirtualTelephony")
    public DataResponse getVirtualTelephony(@RequestBody DriverCallVO callVO) {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            callVO.setFromPhoneNum(hsmwUser.getUsername());
            return hsmwUserService.getDriverVirtualTelephony(callVO);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "司机打电话接出错，请联系管理员！");
        }
    }


    /**
     * 查询司机端的首页的数据
     */
    @Log(title = "查询司机端的首页的数据", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询司机端的首页的数据", notes = "查询司机端的首页的数据", produces = "application/json")
    @PostMapping("/driverHomeInfo")
    public DataResponse driverHomeInfo() {
        try {
            LoginUser hsmwUser = currentHsmwUserUtils.getCurrentUserInfo();
            HsmwUserDriver driver = hsmwUserDriverService.getBizDriverByUserId(hsmwUser.getId());
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            param.put("vehicleId", driver.getVehicleId());
            List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
            result.put("orderList", orderList);
            //查询司机的状态 是 接单中 还是 休息中
            HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>().
                    eq(HsmwUserDriver::getUserId, hsmwUser.getId()));
            String status = "";
            if (StringUtils.isNull(hsmwUserDriver)) {
                status = CommonConstants.DRIVER_FREE;
            } else if (StringUtils.isNull(hsmwUserDriver.getWorkStatus())) {
                status = CommonConstants.DRIVER_FREE;
            } else {
                status = hsmwUserDriver.getWorkStatus();
            }
            result.put("workStatus", status);
            //查询 方量统计
            return new DataResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "查询司机端的首页的数据失败，请联系管理员！");
        }
    }


    /**
     * 查询司机个人信息
     *
     * @return
     */
    @Log(title = "查询司机端个人信息的数据", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询司机端个人信息的数据", notes = "查询司机端个人信息的数据", produces = "application/json")
    @ApiImplicitParam(name = "司机id", value = "id", dataType = "String")
    @PostMapping("findDriUserInfoAndLeasingName")
    public DataResponse findDriUserInfoAndLeasingName(String id) {
        DriverInformationVo driverInformationVo = new DriverInformationVo();

        HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getId, id));
        if (StringUtils.isNotNull(hsmwUserDriver)) {
            HsmwDriverUser hsmwUser = hsmwDriverUserMapper.selectById(hsmwUserDriver.getUserId());
            if (StringUtils.isNotNull(hsmwUser)) {
                driverInformationVo.setUserName(hsmwUser.getName());
                driverInformationVo.setUserPhone(hsmwUser.getUsername());
                driverInformationVo.setAvatar(hsmwUserDriver.getMyPicture());
            }
            String ownCompanyId = hsmwUserDriver.getOwnCompanyId();
            HsmwLeasingCompany hsmwLeasingCompany = hsmwLeasingCompanyMapper.selectById(ownCompanyId);
            if (StringUtils.isNotNull(hsmwLeasingCompany)) {
                driverInformationVo.setLeasingCompanyName(hsmwLeasingCompany.getName());
            }
        }
        return new DataResponse(driverInformationVo);
    }


    @Log(title = "新增或修改user信息", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "新增或修改user信息", notes = "新增或修改user信息", produces = "application/json")
    @PostMapping("saveOrUpdateUser")
    public DataResponse saveOrUpdateUser(@RequestBody HsmwDriverUser hsmwUser) {

        if (hsmwUser != null) {
            if (StringUtils.isNotBlank(hsmwUser.getId())) {
                List<HsmwDriverUser> list = hsmwDriverUserService.list();
                for (HsmwDriverUser user : list) {
                    if (StringUtils.equals(user.getUsername(), hsmwUser.getUsername())) {
                        System.err.println(hsmwUser.getUsername());
                        return new DataResponse<>(CommonConstants.ResponseStatus.FAIL, "手机号重复");
                    }
                }
            }
            hsmwDriverUserService.saveOrUpdateUser(hsmwUser);
        }
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }


    @Log(title = "注销账号 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "注销账号", notes = "注销账号", produces = "application/json")
    @ApiImplicitParam(name = "用户id", value = "id", dataType = "String")
    @PostMapping("deleteHsmwUserById")
    public DataResponse deleteHsmwUserById(String id) {
        HsmwDriverUser user = hsmwDriverUserService.getById(id);
        user.setUsername("该司机账户已注销");
        boolean b = hsmwDriverUserService.updateById(user);
        boolean remove = hsmwUserDriverService.remove(new LambdaQueryWrapper<HsmwUserDriver>()
                .eq(HsmwUserDriver::getUserId, id));
        boolean audit = hsmwAuditService.remove(new LambdaQueryWrapper<HsmwAudit>().eq(HsmwAudit::getUserId, id));
        hsmwOrderService.removeAccount(id);
        redisTemplate.delete(id);
        if (b && remove) {
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
        }
        return new DataResponse(CommonConstants.ResponseStatus.FAIL);
    }


    @ApiOperation(value = "根据车辆id查询车辆下所有司机信息", notes = "根据车辆id查询车辆下所有司机信息", produces = "application/json")
    @ApiImplicitParam(value = "车俩id", name = "id", dataType = "String")
    @PostMapping("findDriverListByVehicleId")
    public DataResponse findDriverListByVehicleId(String id) {
        if (StringUtils.isBlank(id)) {
            return new DataResponse("id不可为空");
        }
        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(id);
        if (StringUtils.isNull(hsmwVehicle)) {
            DataResponse<Object> dataResponse = new DataResponse<>();
            dataResponse.setMessage("车辆信息不存在，请检查！");
            dataResponse.setCode(0);
            dataResponse.setData(new ArrayList<>());
            return dataResponse;
        }

        List<DriverInfo> driverListByVehicleId = hsmwUserDriverService.findDriverListByVehicleId(id);
        return new DataResponse(driverListByVehicleId);
    }


    /**
     * 申请换车
     *
     * @param id
     * @return
     */
    @Log(title = "申请换车 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "申请换车", notes = "申请换车", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "车俩id", name = "id", dataType = "String"),
            @ApiImplicitParam(value = "被换车司机id", name = "driId", dataType = "String")
    })
    @PostMapping("changeTrainsBus")
    @NoRepeatSubmit
    public DataResponse changeTrainsBus(String id, String driId) {

        if (StringUtils.isBlank(id) || StringUtils.isBlank(driId)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数传递错误");
        }
        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(id);
        if (hsmwVehicle == null) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "没有该车辆信息");
        }
        // 当前登录人 信息
        LoginUser currentUserInfo = currentHsmwUserUtils.getCurrentUserInfo();
        if (StringUtils.isNull(currentUserInfo)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "当前登陆人信息错误");
        }

        HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getById(driId);
        if (hsmwUserDriver != null) {
            if (!hsmwUserDriver.getVehicleId().equals(id)) {
                return new DataResponse(CommonConstants.ResponseStatus.FAIL, "操作错误，选择的司机不属于该车");
            }
        } else {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "没有该司机信息");
        }

        List<DriverInfo> driverListByVehicleId = hsmwUserDriverService.findDriverListByVehicleId(id);

        if (driverListByVehicleId.size() > 3) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "车辆超出绑定司机，无法申请");
        }
        // 查询当前登录人的司机信息
        HsmwUserDriver userDriver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getUserId, currentUserInfo.getId()));
        // 查询当前登陆人 是否存在封禁记录
        HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, userDriver.getId()).eq(HsmwBanDriver::getStatus, "1").last("LIMIT 1"));
        if(banDriver != null){
            String format = banDriver.getDurationEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (StringUtils.isNotNull(banDriver)) {
                return new DataResponse(CommonConstants.ResponseStatus.FAIL, "封禁时间还未到期，到期时间：" + format);
            }
        }
        if(hsmwVehicle != null){
            if(StringUtils.isNotBlank(hsmwVehicle.getLeasingCompanyId())){
                if(!StringUtils.equals(userDriver.getOwnCompanyId(),hsmwVehicle.getLeasingCompanyId())){
                    return new DataResponse(FAIL,"不是同一公司，无法进行换车!");
                }
            }
        }
        // 司机状态属于换车中 证明司机没有车辆信息
        if (!StringUtils.equals("换车中", userDriver.getWorkStatus())) {
            for (DriverInfo driverInfo : driverListByVehicleId) {
                if (userDriver.getVehicleId().equals(driverInfo.getVehicleId())) {
                    return new DataResponse(CommonConstants.ResponseStatus.FAIL, "已属于本辆车，无需换车");
                }
            }
        }

        // 提交换车申请
        HsmwExchangeBus hsmwExchangeBus = new HsmwExchangeBus();
        hsmwExchangeBus.setExchangeDriverId(driId);
        hsmwExchangeBus.setDriverId(userDriver.getId());
        hsmwExchangeBus.setVehicleId(id);
        boolean save = hsmwExchangeBusService.save(hsmwExchangeBus);

        HsmwOtherNoticeInfo otherNoticeInfo = new HsmwOtherNoticeInfo();
        otherNoticeInfo.setName(currentUserInfo.getName());
        otherNoticeInfo.setUserId(currentUserInfo.getId());
        otherNoticeInfo.setReadFlag(false);

        otherNoticeInfo.setReportType(OtherNoticeTypeEnum.EXCHANGE_CAR.getValue());
        hsmwOtherNoticeInfoMapper.insert(otherNoticeInfo);


        if (save) {
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
        }
        return new DataResponse(CommonConstants.ResponseStatus.FAIL);
    }


    /**
     * 司机同意或不同意换车申请
     *
     * @param hsmwExchangeBus
     * @return
     */
    @Log(title = "司机同意或不同意换车申请 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机同意或不同意换车申请", notes = "司机同意或不同意换车申请", produces = "application/json")
    @PostMapping("/driverAgree")
    public DataResponse driverAgree(@RequestBody HsmwExchangeBus hsmwExchangeBus) {
        if (StringUtils.isNull(hsmwExchangeBus)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数传递错误");
        }

        //查询被换车的司机信息
        HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getById(hsmwExchangeBus.getExchangeDriverId());
        // 查询申请换车的司机信息
        HsmwUserDriver userDriver = hsmwUserDriverService.getById(hsmwExchangeBus.getDriverId());

        if (StringUtils.isNotBlank(hsmwExchangeBus.getApplyStatus())) {
            //审核通过
            if (StringUtils.equals("1", hsmwExchangeBus.getApplyStatus())) {

                String vehicleId = userDriver.getVehicleId();
                HashMap param = new HashMap();
                param.put("vehicleId", vehicleId);
                if (param.get("vehicleId") != null) {
                    List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
                    if (CollectionUtil.isNotEmpty(orderList)) {
                        return new DataResponse(CommonConstants.ResponseStatus.FAIL, "已有订单，请取消");
                    }
                }
                //司机同意换车 重新赋值
                userDriver.setVehicleId(hsmwUserDriver.getVehicleId());
                userDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
                List<String> ids = hsmwExchangeBus.getIds();
                if (CollectionUtil.isNotEmpty(ids)) {
                    for (String id : ids) {
                        hsmwExchangeBusService.updateExchangeBusStatus(id);
                    }
                }
                hsmwUserDriverService.updateVehicleIdAndWorkStatus(hsmwUserDriver.getId(), CommonConstants.CHANGING_CARS);
                hsmwUserDriverService.updateById(userDriver);
                String key = "driver:status:"+hsmwUserDriver.getId();
                redisTemplate.opsForValue().set(key,LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                hsmwExchangeBusService.updateExBusStatus(hsmwExchangeBus.getExchangeDriverId(), hsmwExchangeBus.getDriverId());
                HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(hsmwUserDriver.getVehicleId());
                if (StringUtils.isNotBlank(userDriver.getUserId())) {
                    HsmwDriverUser user = hsmwDriverUserService.getById(userDriver.getUserId());
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(user.getUsername())) {
                        //回访成功之后 发送推送给司机
                        String msg = "恭喜您换车成功，您现在绑定的车辆为" + hsmwVehicle.getVehiclePlate();
                        //对APP进行离线推送
                        TencentPushUtils.pushMsg(msg, user.getUsername(), "has_new_message");
                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                        hsmwDriverNews.setAlreadyRead("0");
                        hsmwDriverNews.setMessage(msg);
                        hsmwDriverNews.setUserId(userDriver.getUserId());
                        hsmwDriverNewsService.save(hsmwDriverNews);
                    }
                }
            } else {
                hsmwExchangeBusService.updateExchangeBusAllStatus(hsmwExchangeBus.getExchangeDriverId());
                if (CollectionUtil.isNotEmpty(hsmwExchangeBus.getDriverIds())) {
                    for (String id : hsmwExchangeBus.getDriverIds()) {
                        HsmwUserDriver driver = hsmwUserDriverService.getById(id);
                        if (StringUtils.isNotBlank(driver.getUserId())) {
                            HsmwDriverUser user = hsmwDriverUserService.getById(driver.getUserId());
                            if (org.apache.commons.lang3.StringUtils.isNotBlank(user.getUsername())) {
                                //回访成功之后 发送推送给司机
                                String msg = "很遗憾，您的换车申请对方司机没有同意！";
                                //对APP进行离线推送
                                TencentPushUtils.pushMsg(msg, user.getUsername(), "has_new_message");
                                HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                                hsmwDriverNews.setAlreadyRead("0");
                                hsmwDriverNews.setMessage(msg);
                                hsmwDriverNews.setUserId(driver.getUserId());
                                hsmwDriverNewsService.save(hsmwDriverNews);
                            }
                        }
                    }
                }
            }
        }

        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }

    /**
     * 立即加入
     */
    @Log(title = "立即加入 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "立即加入", notes = "立即加入", produces = "application/json")
    @ApiImplicitParam(value = "车俩id", name = "id", dataType = "String")
    @PostMapping("joinNow")
    public DataResponse joinNow(String id) {

        LoginUser user = currentHsmwUserUtils.getCurrentUserInfo();
        if (StringUtils.isNull(user)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "当前登陆人信息错误");
        }
        // 查询申请人的司机信息
        HsmwUserDriver userDriver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getUserId, user.getId()));
        if (StringUtils.equals(id, userDriver.getVehicleId())) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "自己不能换自己啊兄弟");
        }
        HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, userDriver.getId()).eq(HsmwBanDriver::getStatus, "1").last("LIMIT 1"));
        if (StringUtils.isNotNull(banDriver)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "封禁时间还未到期，到期时间：" + banDriver.getDurationEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(id);
        if(hsmwVehicle != null){
            if(StringUtils.isNotBlank(hsmwVehicle.getLeasingCompanyId())){
                if(!StringUtils.equals(userDriver.getOwnCompanyId(),hsmwVehicle.getLeasingCompanyId())){
                    return new DataResponse(FAIL,"不是同一公司，无法进行换车!");
                }
            }
        }
        userDriver.setVehicleId(id);
        userDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
        String key = "driver:status:"+userDriver.getId();
        redisTemplate.opsForValue().set(key,LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        boolean suc = hsmwUserDriverService.updateById(userDriver);
        if (suc) {
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
        }
        return new DataResponse(CommonConstants.ResponseStatus.FAIL);

    }

    /*@Log(title = "司机五分钟取消订单 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机五分钟取消订单", notes = "司机取消订单", produces = "application/json")
    @ApiImplicitParam(value = "司机id", name = "id", dataType = "String")
    @PostMapping("/driverCancelOrder")
    public DataResponse driverCancelOrder(String id){

        if (StringUtils.isBlank(id)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数传递错误，id不可为空");
        }
        HsmwUserDriver driver = hsmwUserDriverMapper.selectById(id);
        if(driver == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"司机信息错误");
        }
        String vehicleId = driver.getVehicleId();
        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(vehicleId);
        List<HsmwUserDriver> list = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, vehicleId));
        for (HsmwUserDriver hsmwUserDriver : list) {
            hsmwUserDriver.setScore(String.valueOf(Long.parseLong(hsmwUserDriver.getScore()) -2));
            HsmwScoringRecord scoringRecord = new HsmwScoringRecord();
            scoringRecord.setRemark("五分钟内取消订单评分-2");
            scoringRecord.setDriverId(hsmwUserDriver.getId());
            scoringRecord.setInitialScore(hsmwUserDriver.getScore());
            scoringRecord.setFluctuateScore("-2");
            scoringRecord.setEndScore(String.valueOf(Long.parseLong(hsmwUserDriver.getScore()) -2));
            hsmwScoringRecordMapper.insert(scoringRecord);
            String ids = hsmwUserDriver.getId();
            HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, ids).eq(HsmwBanDriver::getStatus, "0"));
            if(banDriver == null){
                hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_ACCEPT_ORDER);
            }else {
                hsmwUserDriver.setWorkStatus(CommonConstants.BAN_WORK);
                banDriver.setStatus("1");
                hsmwBanDriverService.updateById(banDriver);
            }
        }
        boolean b = hsmwUserDriverService.updateBatchById(list);
        hsmwVehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
        hsmwVehicleMapper.updateById(hsmwVehicle);

        HashMap param = new HashMap();
        param.put("vehicleId", driver.getVehicleId());
        List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
        for (CurrentOrderInfoVO currentOrderInfoVO : orderList) {
            // 需求id
            String orderVehicleRequestId = currentOrderInfoVO.getOrderVehicleRequestId();
            HsmwOrderVehicleRequest hsmwOrderVehicleRequest = hsmwOrderVehicleRequestMapper.selectById(orderVehicleRequestId);
            if (hsmwOrderVehicleRequest == null) {
                return new DataResponse(CommonConstants.ResponseStatus.FAIL, "该车没有需求信息");
            }
            // 子订单id
            String orderVehicleRelationId = currentOrderInfoVO.getOrderVehicleRelationId();

            //添加取消的记录
            HsmwDriverUser user = hsmwDriverUserService.getById(driver.getUserId());
            HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
            record1.setOrderId(hsmwOrderVehicleRequest.getOrderId());
            record1.setUserType("DRIVER");
            record1.setCreateTime(LocalDateTime.now());
            record1.setName(user.getName());
            record1.setUsername(user.getUsername());
            record1.setOrderStatus(PumpOrderStatusEnum.CANCLED.getValue());
            record1.setOperContent("取消订单！");
            hsmwPumpOperateRecordService.save(record1);

            HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(orderVehicleRelationId);
            // 五分钟之内取消
            HsmwOrder order = hsmwOrderService.getById(currentOrderInfoVO.getOrderId());

            HsmwRequestVehicle hsmwRequestVehicle = new HsmwRequestVehicle();
            hsmwRequestVehicle.setRequestId(orderVehicleRequestId);
            hsmwRequestVehicle.setVehilceId(driver.getVehicleId());
            hsmwRequestVehicle.setForemanUserId(order.getForemanUserId());
            hsmwRequestVehicleMapper.insert(hsmwRequestVehicle);

            if(StringUtils.equals("0",order.getIfConcreteRequired())){
                //泵车订单 取消request releation order
                order.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
                order.setEndTime(LocalDateTime.now());
                order.setRemark("司机取消订单！");
                hsmwOrderService.updateById(order);

                relation.setEndTime(LocalDateTime.now());
                relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
                hsmwOrderVehicleRelationService.updateById(relation);

                hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
                hsmwOrderVehicleRequest.setOperUserId(driver.getUserId());
                hsmwOrderVehicleRequest.setOperType(CommonConstants.NO);
                hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());
                hsmwOrderVehicleRequestMapper.updateById(hsmwOrderVehicleRequest);

                BeanUtilsOrderVO beanUtilsOrderVO = new BeanUtilsOrderVO();
                BeanUtils.copyProperties(order,beanUtilsOrderVO);
                beanUtilsOrderVO.setId(CommonUtils.generateId(beanUtilsOrderVO));
                beanUtilsOrderVO.setCreateTime(LocalDateTime.now());
                hsmwOrderService.saveOrderVo(beanUtilsOrderVO);

                HsmwConstructionPosition position = hsmwConstructionPositionService.getOne(new LambdaQueryWrapper<HsmwConstructionPosition>().eq(HsmwConstructionPosition::getOrderId, order.getId()));
                BeanUtilsPosition beanUtilsPosition = new BeanUtilsPosition();
                BeanUtils.copyProperties(position,beanUtilsPosition);
                beanUtilsPosition.setId(CommonUtils.generateId(beanUtilsPosition));
                beanUtilsPosition.setOrderId(beanUtilsOrderVO.getId());
                hsmwConstructionPositionService.saveBeanPositionVo(beanUtilsPosition);

                BeanUtilsRequestVO beanUtilsRequestVO = new BeanUtilsRequestVO();
                BeanUtils.copyProperties(hsmwOrderVehicleRequest,beanUtilsRequestVO);
                beanUtilsRequestVO.setId(CommonUtils.generateId(beanUtilsRequestVO));
                beanUtilsRequestVO.setRequestStatus(null);
                beanUtilsRequestVO.setOrderId(beanUtilsOrderVO.getId());
                hsmwOrderVehicleRequestMapper.saveRequestInfo(beanUtilsRequestVO);

                placeAnOrderUtils.placeAnOrder(beanUtilsRequestVO.getId());
                HsmwOrderVehicleRequest vehicleRequest = hsmwOrderVehicleRequestService.getById(beanUtilsRequestVO.getId());
                if(vehicleRequest != null){
                    if(StringUtils.isBlank(vehicleRequest.getRequestStatus()) || !StringUtils.equals("2",vehicleRequest.getRequestStatus())){
                        vehicleRequest.setRequestStatus(RequestStatusEnum.UNRECEIVED.getValue());
                    }
                }
                hsmwOrderVehicleRequestMapper.updateById(vehicleRequest);
            }else {
                // 混凝土订单 取消request releation
                relation.setEndTime(LocalDateTime.now());
                relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
                hsmwOrderVehicleRelationService.updateById(relation);

                hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
                hsmwOrderVehicleRequest.setOperUserId(driver.getUserId());
                hsmwOrderVehicleRequest.setOperType(CommonConstants.NO);
                hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());
                hsmwOrderVehicleRequestMapper.updateById(hsmwOrderVehicleRequest);

                BeanUtilsRequestVO beanUtilsRequestVO = new BeanUtilsRequestVO();
                BeanUtils.copyProperties(hsmwOrderVehicleRequest,beanUtilsRequestVO);
                beanUtilsRequestVO.setId(CommonUtils.generateId(beanUtilsRequestVO));
                beanUtilsRequestVO.setRequestStatus(null);
                beanUtilsRequestVO.setOrderId(order.getId());
                hsmwOrderVehicleRequestMapper.saveRequestInfo(beanUtilsRequestVO);

                placeAnOrderUtils.placeAnOrder(beanUtilsRequestVO.getId());
                HsmwOrderVehicleRequest vehicleRequest = hsmwOrderVehicleRequestService.getById(beanUtilsRequestVO.getId());
                if(vehicleRequest != null){
                    if(StringUtils.isBlank(vehicleRequest.getRequestStatus()) || !StringUtils.equals("2",vehicleRequest.getRequestStatus())){
                        vehicleRequest.setRequestStatus(RequestStatusEnum.UNRECEIVED.getValue());
                    }
                }
                hsmwOrderVehicleRequestMapper.updateById(vehicleRequest);
            }

        }
        if(b){
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
        }
        return new DataResponse(CommonConstants.ResponseStatus.FAIL);
    }*/


    @Log(title = "司机已到达之前取消订单 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机已到达之前取消订单", notes = "司机取消订单", produces = "application/json")
    @ApiImplicitParam(value = "司机id", name = "id", dataType = "String")
    @PostMapping("/driverBeforeArrivalCancelOrder")
    public DataResponse driverBeforeArrivalCancelOrder(String id) {

        if (StringUtils.isBlank(id)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数传递错误，id不可为空");
        }
        HsmwUserDriver driver = hsmwUserDriverMapper.selectById(id);

        if (driver == null) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "司机信息错误");
        }
        String vehicleId = driver.getVehicleId();

        HashMap param = new HashMap();
        param.put("vehicleId", driver.getVehicleId());
        List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
        for (CurrentOrderInfoVO currentOrderInfoVO : orderList) {
            // 需求id
            String orderVehicleRequestId = currentOrderInfoVO.getOrderVehicleRequestId();
            HsmwOrderVehicleRequest hsmwOrderVehicleRequest = hsmwOrderVehicleRequestMapper.selectById(orderVehicleRequestId);
            if (hsmwOrderVehicleRequest == null) {
                return new DataResponse(CommonConstants.ResponseStatus.FAIL, "该车没有需求信息");
            }
            // 子订单id
            String orderVehicleRelationId = currentOrderInfoVO.getOrderVehicleRelationId();

            //解散群组
            hsmwOrderService.destoryGroup(orderVehicleRelationId);
            //添加取消的记录
            HsmwDriverUser user = hsmwDriverUserService.getById(driver.getUserId());
            HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
            record1.setOrderId(hsmwOrderVehicleRequest.getOrderId());
            record1.setUserType("DRIVER");
            record1.setCreateTime(LocalDateTime.now());
            record1.setName(user.getName());
            record1.setUsername(user.getUsername());
            record1.setOrderStatus(PumpOrderStatusEnum.CANCLED.getValue());
            record1.setOperContent("取消订单！");
            hsmwPumpOperateRecordService.save(record1);
            HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(orderVehicleRelationId);
            // 到达之前取消 需要向工长发送通知 短信
            HsmwOrder hsmwOrder = hsmwOrderService.getById(currentOrderInfoVO.getOrderId());
            if (StringUtils.isNotNull(hsmwOrder)) {

                if (StringUtils.equals("0", hsmwOrder.getIfConcreteRequired())) {
                    //泵车订单 取消request releation order
                    hsmwOrder.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
                    hsmwOrder.setEndTime(LocalDateTime.now());
                    hsmwOrder.setRemark("司机取消订单！");
                    hsmwOrderService.updateById(hsmwOrder);
                    relation.setCancelOrderFlag("2");
                    relation.setEndTime(LocalDateTime.now());
                    relation.setCancelOrderTime(LocalDateTime.now());
                    relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
                    hsmwOrderVehicleRelationService.updateById(relation);

                    hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
                    hsmwOrderVehicleRequest.setOperUserId(driver.getUserId());
                    hsmwOrderVehicleRequest.setOperType(CancleTypeEnum.DRIVER_CANCEL.getValue());
                    hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());
                    hsmwOrderVehicleRequestMapper.updateById(hsmwOrderVehicleRequest);
                } else {
                    // 混凝土订单 取消request releation
                    relation.setEndTime(LocalDateTime.now());
                    relation.setCancelOrderFlag("2");
                    relation.setCancelOrderTime(LocalDateTime.now());
                    relation.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
                    hsmwOrderVehicleRelationService.updateById(relation);

                    hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
                    hsmwOrderVehicleRequest.setOperUserId(driver.getUserId());
                    hsmwOrderVehicleRequest.setOperType(CancleTypeEnum.DRIVER_CANCEL.getValue());
                    hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());
                    hsmwOrderVehicleRequestMapper.updateById(hsmwOrderVehicleRequest);
                }
                HsmwRequestVehicle hsmwRequestVehicle = new HsmwRequestVehicle();
                hsmwRequestVehicle.setRequestId(orderVehicleRequestId);
                hsmwRequestVehicle.setForemanUserId(hsmwOrder.getItemId());
                hsmwRequestVehicle.setVehilceId(vehicleId);
                hsmwRequestVehicleMapper.insert(hsmwRequestVehicle);
                List<HsmwUserDriver> userDrivers = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, driver.getVehicleId()));
                if (CollectionUtil.isNotEmpty(userDrivers)) {
                    for (HsmwUserDriver userDriver : userDrivers) {
                        HsmwDriverOrderRecord record = new HsmwDriverOrderRecord();
                        record.setDriverId(userDriver.getId());
                        record.setOrderId(currentOrderInfoVO.getOrderId());
                        record.setVehicleNum(relation.getVehicleNum());
                        record.setOrderStatus(ChildOrderStatusEnum.CANCELED.getValue());
                        record.setRelationId(relation.getId());
                        record.setEndTime(LocalDateTime.now());
                        record.setItemName(hsmwOrder.getItemName());
                        record.setItemPosition(hsmwOrder.getItemPosition());
                        record.setRealVolume(hsmwOrder.getExpectVolume());
                        hsmwDriverOrderRecordMapper.insert(record);
                    }
                }


                HsmwHtnUser createUser = hsmwHtnUserService.getById(hsmwOrder.getCreateUser());
                String msgs = "您的泵车订单已被司机取消,请及时查看，如有需要请重新下单";
                //新增系统消息
                HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                hsmwDriverNews.setUserId(createUser.getId());
                hsmwDriverNews.setMessage(msgs);
                hsmwDriverNews.setAlreadyRead("0");
                hsmwDriverNewsService.save(hsmwDriverNews);
                // 企业版
                if (StringUtils.equals(HtnUserTypeEnum.COMPANY.getValue(), createUser.getType()) || StringUtils.equals(HtnUserTypeEnum.PLATFORM.getValue(), createUser.getType())) {

                    WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
                    webSocketReturnVO.setPushId(orderVehicleRequestId);
                    webSocketReturnVO.setStatus(hsmwOrder.getIfConcreteRequired());
                    webSocketReturnVO.setRelationId(relation.getId());
                    webSocketReturnVO.setVehicleId(driver.getVehicleId());
                    TencentPushUtils.selfrunCanCelMsg(msgs, createUser.getUsername(), "has_new_message", webSocketReturnVO);
                    SendSmsUtil.sendDriverSmsCode(appId, appKey, "", driverCancelOrder, smsSign, createUser.getUsername());
                } else {// 项目版
                    WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
                    webSocketReturnVO.setPushId(orderVehicleRequestId);
                    webSocketReturnVO.setStatus(hsmwOrder.getIfConcreteRequired());
                    webSocketReturnVO.setRelationId(relation.getId());
                    webSocketReturnVO.setVehicleId(driver.getVehicleId());
                    TencentPushUtils.pushCancelForeManMsg(msgs, createUser.getUsername(), "has_new_message", webSocketReturnVO);
                    SendSmsUtil.sendDriverSmsCode(appId, appKey, "", driverCancelOrder, smsSign, createUser.getUsername());
                }
            }
        }
        HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(orderList.get(0).getOrderVehicleRelationId());
        List<HsmwDriverCancelOrderRecord> records = new ArrayList<>();

        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(vehicleId);
        List<HsmwUserDriver> list = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, vehicleId));
        for (HsmwUserDriver hsmwUserDriver : list) {
            if (relation.getUpdateTimeFlag() == 0) {
                hsmwUserDriver.setScore(String.valueOf(Long.parseLong(hsmwUserDriver.getScore()) - 20));
                HsmwScoringRecord scoringRecord = new HsmwScoringRecord();
                scoringRecord.setRemark("到达之前取消订单");
                scoringRecord.setDriverId(hsmwUserDriver.getId());
                scoringRecord.setInitialScore(hsmwUserDriver.getScore());
                scoringRecord.setFluctuateScore("-20");
                scoringRecord.setEndScore(String.valueOf(Long.parseLong(hsmwUserDriver.getScore()) - 20));
                hsmwScoringRecordMapper.insert(scoringRecord);
            }

            String ids = hsmwUserDriver.getId();
            HsmwBanDriver banDriver = hsmwBanDriverService.getOne(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getDriverId, ids).eq(HsmwBanDriver::getStatus, "0"));
            if (banDriver == null) {
                hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_ACCEPT_ORDER);
            } else {
                hsmwUserDriver.setWorkStatus(CommonConstants.BAN_WORK);
                HsmwScoringRecord scoringRecord = new HsmwScoringRecord();
                scoringRecord.setDriverId(driver.getId());
                scoringRecord.setInitialScore(driver.getScore());
                scoringRecord.setEndScore(String.valueOf(Long.parseLong(hsmwUserDriver.getScore()) - Long.parseLong(banDriver.getDeductPoints())));
                scoringRecord.setFluctuateScore("-"+banDriver.getDeductPoints());
                scoringRecord.setRemark("封禁扣除评分");
                hsmwScoringRecordMapper.insert(scoringRecord);
                hsmwUserDriver.setScore(String.valueOf(Long.parseLong(hsmwUserDriver.getScore()) - Long.parseLong(banDriver.getDeductPoints())));
                banDriver.setStatus("1");
                hsmwBanDriverService.updateById(banDriver);
            }
            HsmwDriverCancelOrderRecord record = new HsmwDriverCancelOrderRecord();
            HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(hsmwUserDriver.getUserId());
            if (hsmwDriverUser != null && StringUtils.isNotBlank(hsmwDriverUser.getName()) && StringUtils.isNotBlank(hsmwDriverUser.getUsername())) {
                record.setDriverUsername(hsmwDriverUser.getUsername());
                record.setDriverName(hsmwDriverUser.getName());
            }
            record.setDriverId(driver.getId());
            record.setOrderId(relation.getOrderId());
            record.setVehicleNum(relation.getVehicleNum());
            record.setVehicleId(relation.getVehicleId());
            record.setRequestId(relation.getOrderVehicleRequestId());
            record.setOrderStatus(ChildOrderStatusEnum.COMPLETED.getValue());
            record.setRelationId(relation.getId());
            record.setItemName(orderList.get(0).getItemName());
            record.setItemPosition(orderList.get(0).getItemPosition());
            record.setVehicleId(relation.getVehicleId());
            record.setVehicleId(vehicleId);
            record.setConstructionPosition(orderList.get(0).getConstructionPosition());
            //2.2 添加的几个字段
            record.setScore(driver.getScore());
            record.setDriverUserId(driver.getUserId());
            record.setYears(hsmwVehicle.getYears());
            record.setArmSegment(hsmwVehicle.getArmSegment());
            record.setVehicleBrand(hsmwVehicle.getVehicleBrand());
            record.setAxis(hsmwVehicle.getAxis());
            record.setVehicleLeftImage(hsmwVehicle.getVehicleLeftImage());
            record.setVehicleRightImage(hsmwVehicle.getVehicleRightImage());
            record.setDriverUserId(driver.getUserId());
            record.setChassisBrand(hsmwVehicle.getChassisBrand());
            record.setTrafficRate(hsmwVehicle.getTrafficRate());

            records.add(record);
        }
        hsmwDriverCancelOrderRecordService.saveBatch(records);
        boolean b = hsmwUserDriverService.updateBatchById(list);
        hsmwVehicle.setWorkStatus(CommonConstants.VEHICLE_FREE);
        hsmwVehicleMapper.updateById(hsmwVehicle);
        if (b) {
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
        }
        return new DataResponse(CommonConstants.ResponseStatus.FAIL);
    }


    @Log(title = "司机检测 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机检测", notes = "司机检测", produces = "application/json")
    @ApiImplicitParam(value = "司机id", name = "id", dataType = "String")
    @PostMapping("detectionAuthority")
    public DataResponse detectionAuthority(String id) {
        Map map = new HashMap();
        if (StringUtils.isBlank(id)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数传递错误");
        }
        HsmwUserDriver userDriver = hsmwUserDriverService.getById(id);
        if (userDriver == null) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "没有该司机信息");
        }
        String vehicleId = userDriver.getVehicleId();
        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(vehicleId);
        if (hsmwVehicle != null) {
            if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(), hsmwVehicle.getFlag(), hsmwVehicle.getIdentifyingCode());
                map.put("isOnline", entity.getIsOnline());
            }
        }else {
            map.put("isOnline", "0");
        }
        map.put("status", userDriver.getWorkStatus());
        List<HsmwDriverClass> list = hsmwDriverClassService.list(new LambdaQueryWrapper<HsmwDriverClass>().eq(HsmwDriverClass::getDriverId, id));
        if (CollectionUtil.isNotEmpty(list)) {
            for (HsmwDriverClass hsmwDriverClass : list) {
                String progress = hsmwDriverClass.getProgress();
                if (!StringUtils.equals(progress, "100")) {
                    map.put("flag", false);
                    break;
                } else {
                    map.put("flag", true);
                }
            }
        }

        return new DataResponse(map);
    }


    @Log(title = "司机下车 司机端", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机下车", notes = "司机下车", produces = "application/json")
    @ApiImplicitParam(value = "司机id", name = "id", dataType = "String")
    @PostMapping("driverTakeOffice")
    public DataResponse driverTakeOffice(String id) {

        HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getById(id);

        String vehicleId = hsmwUserDriver.getVehicleId();
        HashMap param = new HashMap();
        param.put("vehicleId", vehicleId);
        List<CurrentOrderInfoVO> orderList = hsmwOrderVehicleRelationService.getGoingOrderListByParam(param);
        if (CollectionUtil.isNotEmpty(orderList)) {
            //有进行中订单
            List<HsmwUserDriver> userDrivers = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, vehicleId).eq(HsmwUserDriver::getWorkStatus,CommonConstants.DRIVER_WORK));
            if (CollectionUtil.isNotEmpty(userDrivers) && userDrivers.size() == 1) {
                return new DataResponse(CommonConstants.ResponseStatus.FAIL, "您有进行中的订单，无法下车");

            } else {
                hsmwUserDriver.setVehicleId(null);
                hsmwUserDriver.setWorkStatus(CommonConstants.CHANGING_CARS);
            }
        } else {
            //没有进行中订单
            hsmwUserDriver.setVehicleId(null);
            hsmwUserDriver.setWorkStatus(CommonConstants.CHANGING_CARS);
        }
        return new DataResponse(hsmwUserDriverService.updateById(hsmwUserDriver));
    }


    @Log(title = "司机申请修改预计到达时间", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机申请修改预计到达时间", notes = "司机申请修改预计到达时间", produces = "application/json")
    @PostMapping("updateDriverReachTime")
    public DataResponse updateDriverReachTime(@RequestBody HsmwPushInfo hsmwPushInfo) {

        return hsmwUserDriverService.updateDriverReachTime(hsmwPushInfo);
    }


    @Log(title = "司机查看修改预计到达时间的申请", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查看修改预计到达时间的申请", notes = "司机查看修改预计到达时间的申请", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "String", required = true),
            @ApiImplicitParam(name = "driverId", value = "司机id", dataType = "String", required = true)
    })
    @PostMapping("findDriverReachTimeInfoByOrderId")
    public DataResponse findDriverReachTimeInfoByOrderId(String orderId, String driverId) {

        return hsmwUserDriverService.findDriverReachTimeInfoByOrderId(orderId, driverId);
    }


    @Log(title = "司机查看换车申请 司机端首页", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查看换车申请 司机端首页", notes = "司机查看换车申请 司机端首页", produces = "application/json")
    @ApiImplicitParam(name = "id", value = "司机id", dataType = "String")
    @PostMapping("findExchangeBusBydriverId")
    public DataResponse findExchangeBusBydriverId(String id) {

        return hsmwUserDriverService.findExchangeBusBydriverId(id);
    }

    @ApiOperation(value = "司机查看数据统计折线图", notes = "司机查看数据统计折线图", produces = "application/json")
    @ApiImplicitParam(name = "id", value = "司机id", dataType = "String")
    @PostMapping("driverSeeLineChart")
    public DataResponse driverSeeLineChart(DriverLineChart driverLineChart) throws ParseException {

        if (StringUtils.isNull(driverLineChart)) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "传递参数不能为空");
        }
        return hsmwUserDriverService.driverSeeLineChart(driverLineChart);
    }


    @Log(title = "司机查看系统消息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查看系统消息", notes = "司机查看系统消息", produces = "application/json")
    @PostMapping("driverSeeSystemMessageByUserId")
    public DataResponse driverSeeSystemMessageByUserId() {


        return hsmwUserDriverService.driverSeeSystemMessageByUserId();
    }


    /**
     * 司机评分排行 完成订单排行
     */
    @ApiOperation(value = "司机评分排行 完成订单排行", notes = "司机评分排行 完成订单排行", produces = "application/json")
    @GetMapping("/findDriverScoreRanking")
    public DataResponse findDriverScoreRanking() {


        return hsmwUserDriverService.findDriverScoreRanking();
    }


    /**
     * 帮助中心列表
     */
    @ApiOperation(value = "帮助中心列表", notes = "帮助中心列表", produces = "application/json")
    @PostMapping("/findHelpCenterList")
    public DataResponse findHelpCenterList(@RequestBody @Valid BasePage<HsmwHelpCenter> basePage) {

        IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
        HsmwHelpCenter hsmwHelpCenter = basePage.getRequestData();

        if (page == null) {
            return new DataResponse(FAIL, "分页参数传递不可为空");
        }
        if (hsmwHelpCenter == null) {
            return new DataResponse(FAIL, "传递参数不可为空");
        }

        IPage<HsmwHelpCenter> data = hsmwUserDriverService.findHelpCenterList(page, hsmwHelpCenter);

        return new DataResponse(data);
    }

    /**
     * 查询搜索历史
     *
     * @return 列表查询历史记录，倒序
     */
    @ApiOperation(value = "搜索历史列表", notes = "搜索历史列表", produces = "application/json")
    @GetMapping("/findSearchHistoryListByRedis")
    public DataResponse selectSearchResultList() {
        LoginUser lo = currentHsmwUserUtils.getCurrentUserInfo();
        List<String> searchList = new ArrayList<>();
        String key = "driver:search:" + lo.getId();
        long start = 1;             // 指定开始区间值
        long size = 5;            // 指定长度区间值 （查询搜索历史记录最新的10条）
        Set<ZSetOperations.TypedTuple> scoreWithScores = redisTemplate.opsForZSet().reverseRangeWithScores(key, start - 1, size - 1);
        Iterator<ZSetOperations.TypedTuple> iterator = scoreWithScores.iterator();
        BigDecimal bigDecimal = null;
        while (iterator.hasNext()) {
            ZSetOperations.TypedTuple next = iterator.next();
            bigDecimal = BigDecimal.valueOf(next.getScore());
            if (next.getValue() != null) {
                searchList.add(next.getValue().toString());
            }
        }
        return new DataResponse(searchList);
    }

    @ApiOperation(value = "搜索历史清除全部", notes = "搜索历史清除全部", produces = "application/json")
    @GetMapping("/deleteSearchHistoryListByRedis")
    public DataResponse deleteSearchHistoryListByRedis() {
        LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
        String key = "driver:search:" + loginUser.getId();
        Boolean delete = redisTemplate.delete(key);
        if (delete) {
            return new DataResponse(SUCCESS);
        }
        return new DataResponse(FAIL);
    }


    /**
     * 司机点击有用 没有按钮
     *
     * @param
     * @return
     */
    @ApiOperation(value = "修改帮助中心", notes = "修改帮助中心", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "帮助id", dataType = "String", required = true),
            @ApiImplicitParam(name = "driverId", value = "司机id", dataType = "String", required = true),
            @ApiImplicitParam(name = "params", value = "有用没用参数1 有用 2 没用", dataType = "String", required = false)
    })
    @PostMapping("/updateHelpCenterNum")
    public DataResponse updateHelpCenterNum(String id, String driverId, String params) {


        return hsmwUserDriverService.updateHelpCenterNum(id, driverId, params);
    }


    /**
     * 查看公司合作加油站列表
     */
    @Log(title = "搜索加油站列表", businessType = BusinessType.QUERY)
    @ApiOperation(value = "搜索加油站列表", notes = "搜索历史列表", produces = "application/json")
    @GetMapping("/findGasStationList")
    public DataResponse findGasStationList() {

        return new DataResponse(gasStationMapper.selectList(new LambdaQueryWrapper<>()));
    }

    /**
     * 积分明细
     */
    @Log(title = "司机评分明细列表", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机评分明细列表", notes = "司机评分明细列表", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机id", dataType = "String", required = true),
            @ApiImplicitParam(name = "month", value = "月份", dataType = "String", required = false)
    })
    @GetMapping("/findDriverScoreList")
    public DataResponse findDriverScoreList(String id, String month) {

        Map map = new HashMap();
        if (StringUtils.isBlank(id)) {
            return new DataResponse(FAIL, "传递参数错误");
        }
        List<HsmwScoringRecord> hsmwScoringRecords = hsmwScoringRecordMapper.selectScoreListByDriverId(id, month);
        String endScore = null;
        HsmwUserDriver byId = hsmwUserDriverService.getById(id);
        if (StringUtils.isNotNull(byId)) {
            endScore = byId.getScore();
        }
        String sumScoreByMonth = hsmwScoringRecordMapper.selectScoreListByDriverIdAndMonth(id, month);

        map.put("sumScoreByMonth", sumScoreByMonth);
        map.put("sumScore", endScore == null ? 0 : endScore);
        map.put("hsmwScoringRecords", hsmwScoringRecords);

        return new DataResponse(map);
    }

    @Log(title = "司机方量结算", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机方量结算", notes = "司机方量结算", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机id", dataType = "String", required = true),
            @ApiImplicitParam(name = "year", value = "年", dataType = "String", required = true),
            @ApiImplicitParam(name = "month", value = "月份", dataType = "String", required = false)
    })
    @GetMapping("/findDriverVolumesInfo")
    public DataResponse findDriverVolumesInfo(String id, String month) {

        if (StringUtils.isBlank(id)) {
            return new DataResponse(FAIL, "传递参数错误");
        }
        String types = "1,2,3";
        String[] split = types.split(",");
        for (String s : split) {
            String key = "driver:List:"+s+":"+id;
            redisTemplate.delete(key);
        }

        return new DataResponse(hsmwUserDriverService.findDriverVolumesInfo(id, month));
    }


    @Log(title = "保存或者修改司机投诉信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "保存或者修改司机投诉信息", notes = "保存或者修改司机投诉信息", produces = "application/json")
    @PostMapping("/saveOrUpdateDriverComplian")
    public DataResponse saveOrUpdateDriverComplian(@RequestBody HsmwDriverComplain hsmwDriverComplain) {

        if (StringUtils.isNull(hsmwDriverComplain)) {
            return new DataResponse(FAIL, "传递参数不可为空");
        }

        return new DataResponse(hsmwUserDriverService.saveOrUpdateDriverComplian(hsmwDriverComplain));

    }

    /**
     * 查看司机投诉信息列表
     */
    @Log(title = "查看司机投诉信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查看司机投诉信息", notes = "查看司机投诉信息", produces = "application/json")
    @GetMapping("/findDriverComplianList")
    public DataResponse findDriverComplianList(@RequestBody HsmwDriverComplain hsmwDriverComplain) {

        return hsmwUserDriverService.findDriverComplianList(hsmwDriverComplain);
    }


    @Log(title = "司机分享新增积分", businessType = BusinessType.QUERY)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机Id", dataType = "String", required = true),
            @ApiImplicitParam(name = "score", value = "增加积分", dataType = "String", required = true)
    })
    @ApiOperation(value = "司机分享新增积分", notes = "保存或者修改司机投诉信息", produces = "application/json")
    @PostMapping("/driverShare")
    public DataResponse driverShare(String id, String score) {

        if (StringUtils.isBlank(id) || StringUtils.isBlank(score)) {
            return new DataResponse(FAIL, "传递参数不可为空");
        }
        String key = "driver:share:" + id;

        HsmwUserDriver userDriver = hsmwUserDriverService.getById(id);
        if (userDriver != null) {
            userDriver.setDriverIntegral(String.valueOf(Long.parseLong(userDriver.getDriverIntegral()) + Long.parseLong(score)));
        }
        redisTemplate.opsForValue().set(key, id);
        boolean b = hsmwUserDriverService.updateById(userDriver);
        if (b) {
            return new DataResponse(SUCCESS);
        }
        return new DataResponse(FAIL);
    }


    @Log(title = "查询车辆所有的信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询车辆所有的信息", notes = "查询车辆所有的信息", produces = "application/json")
    @ApiImplicitParam(name = "id",value = "司机id",dataType = "String",required = true)
    @GetMapping("/queryVehicleByDriverInfo")
    public DataResponse queryVehicleByDriverInfo(String id) {
        VehicleByDriverVO vehicleByDriverVO = new VehicleByDriverVO();

        //司机信息
        HsmwUserDriver userDriver = hsmwUserDriverService.getById(id);

        //车辆信息
        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(userDriver.getVehicleId());
        if(hsmwVehicle != null){
            vehicleByDriverVO.setVehicleModel(hsmwVehicle.getVehicleModel());
            vehicleByDriverVO.setVehicleType(hsmwVehicle.getVehicleType());
            vehicleByDriverVO.setVehiclePlate(hsmwVehicle.getVehiclePlate());
            vehicleByDriverVO.setVehicleLeftImage(hsmwVehicle.getVehicleLeftImage());

            Date localDate = Date.from(LocalDate.now().atStartOfDay(ZoneOffset.ofHours(8)).toInstant());

            Date compuTrafficTime = Date.from(hsmwVehicle.getCompuTrafficTime().atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
            Date commercialInsuranceTime = Date.from(hsmwVehicle.getCommercialInsuranceTime().atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
            Date drivingLicenseTime = Date.from(hsmwVehicle.getDrivingLicenseTime().atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
            // 交强险
            int offsetDays = DateUtil.getOffsetDays(localDate, compuTrafficTime);
            //商业险
            int commercialDays = DateUtil.getOffsetDays(localDate, commercialInsuranceTime);
            // 行驶证
            int drivingDays = DateUtil.getOffsetDays(localDate, drivingLicenseTime);

            vehicleByDriverVO.setDrivingLicenseDays(drivingDays);
            vehicleByDriverVO.setCommicialEnsurendeDays(commercialDays);
            vehicleByDriverVO.setTrafficEnsurendeDays(offsetDays);

            List<DriverDetailInfoVO> driverDetailInfoVOs = new ArrayList<>();
            //车辆下的司机信息
            List<HsmwUserDriver> list = hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, hsmwVehicle.getId()));
            if (CollectionUtil.isNotEmpty(list)) {
                for (HsmwUserDriver driver : list) {
                    if(StringUtils.equals(driver.getId(),id)){
                        continue;
                    }
                    HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(driver.getUserId());
                    DriverDetailInfoVO driverDetailInfoVO = new DriverDetailInfoVO();
                    driverDetailInfoVO.setName(hsmwDriverUser.getName());
                    driverDetailInfoVO.setUsername(hsmwDriverUser.getUsername());
                    driverDetailInfoVO.setAvatar(driver.getMyPicture());
                    driverDetailInfoVO.setUserId(hsmwDriverUser.getId());
                    driverDetailInfoVOs.add(driverDetailInfoVO);
                }
            }
            if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(), hsmwVehicle.getFlag(), hsmwVehicle.getIdentifyingCode());
                vehicleByDriverVO.setIsOnline(entity.getIsOnline());
            }
            vehicleByDriverVO.setDriverDetailInfoVOs(driverDetailInfoVOs);
        }
        return new DataResponse(vehicleByDriverVO);
    }



    @Log(title = "根据订单id查询订单信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "根据订单id查询订单信息", notes = "根据订单id查询订单信息", produces = "application/json")
    @ApiImplicitParam(name = "id",value = "订单id",dataType = "String",required = true)
    @GetMapping("/queryOrderInfoById")
    public DataResponse queryOrderInfoById(String id,String flag){

        if(StringUtils.isBlank(id)){
            return new DataResponse(FAIL,"id不可为空");
        }
        QueryOrderDetailVO queryOrderDetailVO = hsmwUserDriverService.queryOrderInfoById(id,flag);
        return new DataResponse(queryOrderDetailVO);
    }

    @Log(title = "司机确认挪泵 空跑 结算明细", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机确认挪泵 空跑 结算明细", notes = "司机确认查询挪泵 空跑 结算明细", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "司机id",dataType = "String",required = true),
            @ApiImplicitParam(name = "type",value = "类型 1 挪泵 2 空跑 3 结算",dataType = "String",required = true)
    })
    @PostMapping("saveDriverConfirmDetailed")
    public DataResponse saveDriverConfirmDetailed(@RequestBody List<MoveAndRunVO> list,String id,String type){

        String key = "driver:List:"+type+":"+id;

        redisTemplate.opsForValue().set(key,list);

        return new DataResponse(SUCCESS);
    }


    @Log(title = "查询挪泵 空跑 结算明细", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询挪泵 空跑 结算明细", notes = "查询挪泵 空跑 结算明细", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "司机id",dataType = "String",required = true),
            @ApiImplicitParam(name = "month",value = "月份 yyyy-MM",dataType = "String",required = true),
            @ApiImplicitParam(name = "type",value = "类型 1 挪泵 2 空跑 3 结算",dataType = "String",required = true)
    })
    @GetMapping("/quertDriverMoveAndRunList")
    public DataResponse quertDriverMoveAndRunList(String id,String type,String month) {
        if (StringUtils.isBlank(id) || StringUtils.isBlank(type)) {
            return new DataResponse(FAIL, "传递参数错误，请检查");
        }
        List<MoveAndRunVO> list = new ArrayList<>();
        String key = "driver:List:"+type+":"+id;

        if (StringUtils.equals("1", type)) {
            if(redisTemplate.hasKey(key)){
                list = (List<MoveAndRunVO>) redisTemplate.opsForValue().get(key);
            }else {
                list = hsmwOrderBalanceMapper.queryDriverMoveList(id,month);
            }

        } else if (StringUtils.equals("2", type)) {

            if(redisTemplate.hasKey(key)){
                list = (List<MoveAndRunVO>) redisTemplate.opsForValue().get(key);
            }else {
                list = hsmwRunSprintRecordMapper.queryRunList(id,month);
            }

        } else {

            if(redisTemplate.hasKey(key)){
                list = (List<MoveAndRunVO>) redisTemplate.opsForValue().get(key);
            }else {
                list = hsmwDriverOrderRecordMapper.queryDriverOrderList(id,month);
            }
        }
        return new DataResponse(list);
    }

    @Log(title = "退出明细", businessType = BusinessType.QUERY)
    @ApiOperation(value = "退出明细", notes = "退出明细", produces = "application/json")
    @ApiImplicitParam(name = "id",value = "司机id",dataType = "String",required = true)
    @PostMapping("deleteDriverDetailed")
    public DataResponse deleteDriverDetailed(String id,String types){

        String[] split = types.split(",");
        for (String s : split) {
            String key = "driver:List:"+s+":"+id;
            redisTemplate.delete(key);
        }
        return new DataResponse(SUCCESS);
    }


    @Log(title = "根据司机id查询自动签到状态", businessType = BusinessType.QUERY)
    @ApiOperation(value = "根据司机id查询自动签到状态", notes = "根据司机id查询自动签到状态", produces = "application/json")
    @ApiImplicitParam(name = "id",value = "司机id",dataType = "String",required = true)
    @GetMapping("/quertRedisVehicleAutomatorStatus")
    public DataResponse quertRedisVehicleAutomatorStatus(String id){
        if(StringUtils.isBlank(id)){
            return new DataResponse(FAIL,"传递参数错误，请检查");
        }
        HsmwUserDriver userDriver = hsmwUserDriverMapper.selectById(id);
        if(StringUtils.isNull(userDriver)){
            return new DataResponse(FAIL,"没有司机信息，请检查");
        }
        String key = "vehicle:automatic:"+userDriver.getVehicleId();
        if(redisTemplate.hasKey(key)){
            return new DataResponse(SUCCESS,true);
        }
        return new DataResponse(SUCCESS,false);
    }

    @Log(title = "司机查询公司服务", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查询公司服务", notes = "司机查询公司服务", produces = "application/json")
    @GetMapping("/queryDriverCompanyServices")
    public DataResponse queryDriverCompanyServices(){

        DriverCompanyVO driverCompanyVO = new DriverCompanyVO();

        LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
        if(loginUser == null){
            return new DataResponse(FAIL,"当前登陆人信息错误");
        }
        String id = loginUser.getId();
        HsmwUserDriver userDriver = hsmwUserDriverMapper.selectOne(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getUserId, id));
        if(StringUtils.isNotNull(userDriver) && StringUtils.isNotBlank(userDriver.getOwnCompanyId())){
            HsmwLeasingCompany hsmwLeasingCompany = hsmwLeasingCompanyMapper.selectById(userDriver.getOwnCompanyId());
            if(StringUtils.isNotNull(hsmwLeasingCompany) && StringUtils.isNotBlank(hsmwLeasingCompany.getName())){
                driverCompanyVO.setCompanyType("泵送公司");
                driverCompanyVO.setCompanyName(hsmwLeasingCompany.getName());
            }

            List<HsmwHtnUser> hsmwHtnUsers = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>().eq(HsmwHtnUser::getOwnCompanyId, userDriver.getOwnCompanyId()));
            List<DriverDetailInfoVO> list = new ArrayList<>();
            hsmwHtnUsers.stream().forEach(hsmwHtnUser -> {
                DriverDetailInfoVO driverDetailInfoVO = new DriverDetailInfoVO();
                driverDetailInfoVO.setAvatar(hsmwHtnUser.getAvatar());
                driverDetailInfoVO.setName(hsmwHtnUser.getName());
                driverDetailInfoVO.setUsername(hsmwHtnUser.getUsername());
                if(StringUtils.equals(HtnUserRoleEnum.LEADING.getValue(),hsmwHtnUser.getRoleType())){
                    driverDetailInfoVO.setScore(HtnUserRoleEnum.LEADING.getName());
                }else if(StringUtils.equals(HtnUserRoleEnum.DISPATCH.getValue(),hsmwHtnUser.getRoleType())){
                    driverDetailInfoVO.setScore(HtnUserRoleEnum.DISPATCH.getName());
                }else {
                    driverDetailInfoVO.setScore("其他");
                }
                list.add(driverDetailInfoVO);
            });
            driverCompanyVO.setDriverDetailInfoVOS(list);
            if(StringUtils.isNotBlank(userDriver.getVehicleId())){
                HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(userDriver.getVehicleId());
                driverCompanyVO.setVehicleNumber(hsmwVehicle.getVehiclePlate());
            }
        }
        return new DataResponse(driverCompanyVO);
    }


    @Log(title = "司机重新回到工作中", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机重新回到工作中", notes = "司机重新回到工作中", produces = "application/json")
    @ApiImplicitParam(name = "id",value = "订单id",dataType = "String",required = true)
    @PostMapping("updateOrderWorkStatusById")
    public DataResponse updateOrderWorkStatusById(String id){
        if(StringUtils.isBlank(id)){
            return new DataResponse(FAIL,"传递参数错误，请检查！");
        }
        boolean suc  = hsmwOrderService.updateOrderWorkStatusById(id);
        if(suc){
            return new DataResponse(SUCCESS);
        }
        return new DataResponse(FAIL);
    }

    @Log(title = "根据司机所在的公司查询公司下的项目", businessType = BusinessType.QUERY)
    @ApiOperation(value = "根据司机所在的公司查询公司下的项目", notes = "根据司机所在的公司查询公司下的项目", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "司机id",dataType = "String",required = true),
            @ApiImplicitParam(name = "locate",value = "司机位置",dataType = "String",required = true)
    })
    @GetMapping("queryDriverCompanyForItemByDriverId")
    public DataResponse queryDriverCompanyForItemByDriverId(String id,String locate){
        if(StringUtils.isBlank(id) || StringUtils.isBlank(locate)) {
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED);
        }

        List<HsmwItem> list = hsmwUserDriverService.queryDriverCompanyForItemByDriverId(id,locate);

        return new DataResponse(list);
    }



    @Log(title = "根据司机所在的公司id查询公司下的所有司机", businessType = BusinessType.QUERY)
    @ApiOperation(value = "根据司机所在的公司id查询公司下的所有司机", notes = "根据司机所在的公司id查询公司下的所有司机", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "司机id",dataType = "String",required = true)
    })
    @GetMapping("queryDriverCompanyForDriverInfoByDriverId")
    public DataResponse queryDriverCompanyForDriverInfoByDriverId(String id){
        if(StringUtils.isBlank(id)) {
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED);
        }

        HsmwUserDriver userDriver = hsmwUserDriverMapper.selectById(id);
        List<DriverDetailInfoVO> driverDetailInfoVOs = new ArrayList<>();
        if(StringUtils.isNotNull(userDriver) && StringUtils.isNotBlank(userDriver.getOwnCompanyId())){
            List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getOwnCompanyId, userDriver.getOwnCompanyId()));
            if(CollectionUtil.isNotEmpty(hsmwUserDrivers)){
                for (HsmwUserDriver hsmwUserDriver : hsmwUserDrivers) {
                    if(userDriver.getId().equals(hsmwUserDriver.getId())){
                        continue;
                    }
                    DriverDetailInfoVO driverDetailInfoVO = new DriverDetailInfoVO();
                    HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(hsmwUserDriver.getUserId());
                    if(StringUtils.equals(userDriver.getVehicleId(),hsmwUserDriver.getVehicleId())){
                        driverDetailInfoVO.setScore("当前同车");
                    }
                    driverDetailInfoVO.setDriverId(hsmwUserDriver.getId());
                    driverDetailInfoVO.setName(hsmwDriverUser.getName());
                    driverDetailInfoVO.setUsername(hsmwDriverUser.getUsername());
                    driverDetailInfoVO.setAvatar(hsmwUserDriver.getMyPicture());
                    driverDetailInfoVOs.add(driverDetailInfoVO);
                }
            }
        }
        return new DataResponse(driverDetailInfoVOs);
    }


    @Log(title = "订单录入新增", businessType = BusinessType.QUERY)
    @ApiOperation(value = "订单录入新增", notes = "订单录入新增", produces = "application/json")
    @PostMapping("addDriverOrderRecordInfoByDriver")
    public DataResponse addDriverOrderRecordInfoByDriver(@RequestBody DriverOrderRecordDTO driverOrderRecordDTO){

        if(StringUtils.isNull(driverOrderRecordDTO)){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED);
        }

        return hsmwDriverUserService.addDriverOrderRecordInfoByDriver(driverOrderRecordDTO);
    }


    /**
     *查询通讯录
     */
    @Log(title = "查询通讯录 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询通讯录", notes = "查询通讯录", produces = "application/json")
    @PostMapping("/queryAddressList")
    public DataResponse queryAddressList() {
        List<DriverAddressInfo> info = new ArrayList<>();
        HsmwDriverUser currentHtnUser = currentHsmwUserUtils.getCurrentDriverUserInfo();
        HsmwUserDriver driverInfo  = hsmwUserDriverService.getBizDriverByUserId(currentHtnUser.getId());
        if(StringUtils.isNotNull(driverInfo) && StringUtils.isNotBlank(driverInfo.getOwnCompanyId())){
            HashMap param = new HashMap();
            param.put("ownCompanyId",driverInfo.getOwnCompanyId());
            param.put("userId",currentHtnUser.getId());
            info = hsmwHtnUserService.queryAddressList(param);
        }
        return  new DataResponse(info);
    }

    @Log(title = "查询聊天的人是否在同一公司 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询聊天的人是否在同一公司", notes = "查询聊天的人是否在同一公司", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "当前司机id ",dataType = "String",required = true),
            @ApiImplicitParam(name = "userId",value = "对方司机id ",dataType = "String",required = true),
            @ApiImplicitParam(name = "type",value = "类型,1:司机2：其他 ",dataType = "String",required = true)
    })
    @GetMapping("/queryDriverChatForCompany")
    public DataResponse queryDriverChatForCompany(String id,String userId,String type) {

        if (StringUtils.isBlank(id) || StringUtils.isBlank(userId)) {
            return new DataResponse(FAIL, "传递参数错误，请检查！");
        }
        //当前司机
        HsmwUserDriver userDriver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getUserId, id));
        if (userDriver == null) {
            return new DataResponse(FAIL, "查询错误");
        }
        if (StringUtils.equals("1", type)) {
            //对方司机
            HsmwUserDriver driver = hsmwUserDriverService.getOne(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getUserId, userId));
            if (driver == null) {
                return new DataResponse(FAIL, "查询错误");
            }
            if (StringUtils.equals(userDriver.getOwnCompanyId(), driver.getOwnCompanyId())) {
                return new DataResponse(SUCCESS, true);
            } else {
                return new DataResponse(SUCCESS, false);
            }
        } else {
            HsmwHtnUser byId = hsmwHtnUserService.getById(userId);
            if (byId == null) {
                return new DataResponse(FAIL, "查询错误");
            }
            if (StringUtils.isNotBlank(byId.getOwnCompanyId()) && StringUtils.equals(byId.getOwnCompanyId(), userDriver.getOwnCompanyId())) {
                return new DataResponse(SUCCESS, true);
            } else {
                return new DataResponse(SUCCESS, false);
            }
        }
    }


    /**
     *移除聊天用户
     */
    @Log(title = "司机移除聊天用户 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "移除聊天用户", notes = "移除聊天用户", produces = "application/json")
    @PostMapping("/removeIMUser")
    public DataResponse removeIMUser(String  userId) {

        hsmwOrderService.removeAccount(userId);

        return  new DataResponse();
    }


    @Log(title = "司机获取当前车辆的位置信息 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机获取当前车辆的位置信息", notes = "司机获取当前车辆的位置信息", produces = "application/json")
    @ApiImplicitParam(name = "id", value = "司机id", dataType = "Stirng", required = true)
    @GetMapping("/queryVechicleGPSInfo")
    public  DataResponse queryVechicleGPSInfo(String id){
        if(StringUtils.isBlank(id)){
            return new DataResponse(FAIL,"司机id不可为空");
        }
        HsmwUserDriver userDriver = hsmwUserDriverService.getById(id);
        if(StringUtils.isNull(userDriver)){
            return new DataResponse(FAIL,"没有该司机信息");
        }
        String imeiNumLocate = null;
        if(StringUtils.isNotBlank(userDriver.getVehicleId())){
            HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(userDriver.getVehicleId());
            if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
                GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(), hsmwVehicle.getFlag(), hsmwVehicle.getIdentifyingCode());
                if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
                    imeiNumLocate = (entity.getGpsLon() + "," + entity.getGpsLat());
                }
            }
        }
        return new DataResponse(SUCCESS,imeiNumLocate);
    }


    @Log(title = "司机进行位置纠错 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机进行位置纠错", notes = "司机获取当前车辆的位置信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "relationId", value = "子订单id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "lng", value = "经度", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "lat", value = "纬度", dataType = "Stirng", required = true)
    })
    @PostMapping("/updateSituationReport")
    public DataResponse updateSituationReport(String id, String orderId, String relationId, String lng, String lat){

        if(StringUtils.isBlank(id) || StringUtils.isBlank(orderId)){
            return new DataResponse(FAIL,"传递参数错误，请检查");
        }
        HsmwDriverUser driverUser = currentHsmwUserUtils.getCurrentDriverUserInfo();
        // 汇报情况实体类HsmwSituationReportService
        HsmwSituationReport hsmwSituationReport = new HsmwSituationReport();
        hsmwSituationReport.setDriverId(id);
        hsmwSituationReport.setOrderId(orderId);
        hsmwSituationReport.setRelationId(relationId);
        hsmwSituationReport.setLat(lat);
        hsmwSituationReport.setLng(lng);
        hsmwSituationReport.setUserId(driverUser.getId());
        String nameByGps = GaoDeInfoUtils.gaodeGetNameByGps(lng+","+lat);
        hsmwSituationReport.setAddress(nameByGps);
        boolean save = hsmwSituationReportService.save(hsmwSituationReport);

        HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getById(id);
        if(hsmwUserDriver == null){
            return new DataResponse(FAIL,"司机信息错误");
        }
        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(hsmwUserDriver.getVehicleId());
        if(hsmwVehicle == null){
            return new DataResponse(FAIL,"该司机没有车辆信息");
        }
        HsmwDriverUser hsmwDriverUser = hsmwDriverUserMapper.selectById(hsmwUserDriver.getUserId());
        if(hsmwDriverUser == null){
            return new DataResponse(FAIL,"司机个人信息查询错误");
        }
        HsmwOrder order = hsmwOrderService.getById(orderId);
        HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(relationId);
        HsmwHtnUser foremanUser = hsmwHtnUserService.getById(order.getCreateUser());

        String message = order.getItemName()+"项目订单"+hsmwVehicle.getVehiclePlate()+","+hsmwDriverUser.getName()+"司机发现项目位置不准确，已提交新项目位置，请抓紧查看并修改。";
        String  foremanUserId = order.getCreateUser();
        String  foremanUsername = foremanUser.getUsername();
        //新增系统消息
        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
        hsmwDriverNews.setUserId(foremanUserId);
        hsmwDriverNews.setMessage(message);
        hsmwDriverNews.setAlreadyRead("0");
        hsmwDriverNewsService.save(hsmwDriverNews);
        WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
        webSocketReturnVO.setRelationId(relation.getId());
        TencentPushUtils.selfrunCanCelMsg(message,foremanUsername,"has_new_message",webSocketReturnVO);

        String[] params = new String[]{order.getItemName(),hsmwVehicle.getVehiclePlate(),hsmwDriverUser.getName()};
        SendSmsUtil.sendSmsWithParam(appId, appKey, params, positionErrorRecovery, smsSign, foremanUsername);

        if(save){
            return new DataResponse(SUCCESS);
        }
        return new DataResponse(FAIL);
    }

    @Log(title = "司机查看是否提交位置纠错 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查看是否提交位置纠错", notes = "司机获取当前车辆的位置信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "Stirng", required = true)
    })
    @PostMapping("/querySituationReportInfoById")
    public DataResponse querySituationReportInfoById(String id,String orderId){

        if(StringUtils.isBlank(id)){
            return new DataResponse(FAIL,"传递参数错误");
        }
        HsmwSituationReport one = hsmwSituationReportService.getOne(new LambdaQueryWrapper<HsmwSituationReport>().eq(HsmwSituationReport::getDriverId, id).eq(HsmwSituationReport::getOrderId,orderId).eq(HsmwSituationReport::getStatus, "0").last("LIMIT 1"));
        if(StringUtils.isNotNull(one)){
            return new DataResponse(SUCCESS,true);
        }
        return new DataResponse(SUCCESS,false);
    }



    @Log(title = "司机汇报上报情况信息 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机汇报上报情况信息", notes = "司机获取当前车辆的位置信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "relationId", value = "子订单id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "duration", value = "工作时长 百分比或者小时", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "type", value = "1：记录50% 2：时长", dataType = "Stirng", required = true)
    })
    @PostMapping("/updateWorkProgressInfo")
    public DataResponse updateWorkProgressInfo(String id,String relationId,String duration,String type){


        HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(relationId);
        if(relation == null){
            return new DataResponse(FAIL,"子订单信息错误");
        }

        HsmwOrder order = hsmwOrderService.getById(relation.getOrderId());
        if(order == null){
            return new DataResponse(FAIL,"主订单信息错误");
        }

        HsmwHtnUser foremanUser = hsmwHtnUserService.getById(order.getCreateUser());
        if(foremanUser == null){
            return new DataResponse(FAIL,"订单创建人信息查询错误");
        }

        HsmwUserDriver hsmwUserDriver = hsmwUserDriverService.getById(id);
        if(hsmwUserDriver == null){
            return new DataResponse(FAIL,"司机信息错误");
        }

        HsmwVehicle hsmwVehicle = hsmwVehicleMapper.selectById(hsmwUserDriver.getVehicleId());
        if(hsmwVehicle == null){
            return new DataResponse(FAIL,"该司机没有车辆信息");
        }
        if(relation != null){
            if(StringUtils.equals("1",type)){
                relation.setWorkProgress(duration);
                String message = order.getItemName()+"项目订单"+hsmwVehicle.getVehiclePlate()+"已完成50%工作";
                String  foremanUserId = order.getCreateUser();
                String  foremanUsername = foremanUser.getUsername();
                //新增系统消息
                HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                hsmwDriverNews.setUserId(foremanUserId);
                hsmwDriverNews.setMessage(message);
                hsmwDriverNews.setAlreadyRead("0");
                hsmwDriverNewsService.save(hsmwDriverNews);
                WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
                webSocketReturnVO.setRelationId(relation.getId());
                TencentPushUtils.selfrunCanCelMsg(message,foremanUsername,"has_new_message",webSocketReturnVO);
                String[] params = new String[]{order.getItemName(),hsmwVehicle.getVehiclePlate()};
                SendSmsUtil.sendSmsWithParam(appId, appKey, params, workFinishFive, smsSign, foremanUsername);
            }else {
                relation.setDuration(duration);
                Double aDouble = Double.valueOf(duration) * 60;
                long l = new Double(aDouble).longValue();
                relation.setReportingTime(LocalDateTime.now().plusMinutes(l));
                String message = order.getItemName()+"项目订单"+hsmwVehicle.getVehiclePlate()+"预计"+duration+"小时后完成工作";
                String  foremanUserId = order.getCreateUser();
                String  foremanUsername = foremanUser.getUsername();
                //新增系统消息
                HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                hsmwDriverNews.setUserId(foremanUserId);
                hsmwDriverNews.setMessage(message);
                hsmwDriverNews.setAlreadyRead("0");
                hsmwDriverNewsService.save(hsmwDriverNews);
                WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
                webSocketReturnVO.setRelationId(relation.getId());
                TencentPushUtils.selfrunCanCelMsg(message,foremanUsername,"has_new_message",webSocketReturnVO);
                String[] params = new String[]{order.getItemName(),hsmwVehicle.getVehiclePlate(),duration};
                SendSmsUtil.sendSmsWithParam(appId, appKey, params, workFinishHour, smsSign, foremanUsername);
            }
        }

        boolean update = hsmwOrderVehicleRelationService.updateById(relation);
        if(update){
            return new DataResponse(SUCCESS);
        }
        return new DataResponse(FAIL);
    }






    @Log(title = "司机查看是否进行工作情况汇报 ", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查看是否进行工作情况汇报", notes = "司机获取当前车辆的位置信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "relationId", value = "子订单id", dataType = "Stirng", required = true)
    })
    @GetMapping("/queryWorkProgressInfoById")
    public DataResponse queryWorkProgressInfoById(String id,String relationId){

        if(StringUtils.isBlank(id) || StringUtils.isBlank(relationId)){
            return new DataResponse(FAIL,"传递参数错误");
        }
        Map<String,String> map =new HashMap<>();
        HsmwOrderVehicleRelation relation = hsmwOrderVehicleRelationService.getById(relationId);
        if(StringUtils.isNotNull(relation)){
            map.put("percentage",relation.getWorkProgress());
            map.put("hour",relation.getDuration());
        }
        return new DataResponse(SUCCESS,map);
    }


    @Log(title = "司机查看帮助中心是否点击", businessType = BusinessType.QUERY)
    @ApiOperation(value = "司机查看帮助中心是否点击", notes = "司机获取当前车辆的位置信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "司机id", dataType = "Stirng", required = true),
            @ApiImplicitParam(name = "helpId", value = "帮助中心id", dataType = "Stirng", required = true)
    })
    @GetMapping("/queryHelpCenterInfoByHelpId")
    public DataResponse queryHelpCenterInfoByHelpId(String id, String helpId){


        return hsmwUserDriverService.queryHelpCenterInfoByHelpId(id,helpId);
    }


    @Log(title = "查询司机同一公司的车辆信息", businessType = BusinessType.QUERY)
    @ApiOperation(value = "查询司机同一公司的车辆信息", notes = "司机获取当前车辆的位置信息", produces = "application/json")
    @ApiImplicitParam(name = "id", value = "司机id", dataType = "Stirng", required = true)
    @GetMapping("/queryVehicleInfoBuDriverId")
    public DataResponse queryVehicleInfoBuDriverId(String id) {

        HsmwUserDriver byId = hsmwUserDriverService.getById(id);
        if (byId == null) {
            return new DataResponse(FAIL, "查询司机信息错误");
        }
        List<HsmwVehicle> hsmwVehicles = null;
        if (StringUtils.isNotBlank(byId.getOwnCompanyId())) {
            hsmwVehicles = hsmwVehicleMapper.selectList(new LambdaQueryWrapper<HsmwVehicle>().eq(HsmwVehicle::getLeasingCompanyId, byId.getOwnCompanyId()));
        }
        return new DataResponse(SUCCESS, hsmwVehicles);
    }


}
